首页 >数据库 >mysql教程 >如何在旧 PostgreSQL 版本中使用 `(func()).*` 防止多个函数调用?

如何在旧 PostgreSQL 版本中使用 `(func()).*` 防止多个函数调用?

DDD
DDD原创
2025-01-10 10:57:42438浏览

How to Prevent Multiple Function Calls with `(func()).*` in Older PostgreSQL Versions?

在旧版 PostgreSQL 版本中使用 (func()).* 避免重复函数调用

问题

在 9.3 之前的 PostgreSQL 版本中,使用 (func()).* 语法(其中 func 返回表)可能会导致函数意外多次执行。这会显着影响查询性能。

解决方案

有几种方法可以有效规避这个问题:

1。子查询方法:

<code class="language-sql">SELECT (mf).* FROM (
    SELECT my_func(x) AS mf FROM some_table
) sub;</code>

2。 OFFSET 0 技术:

<code class="language-sql">SELECT (mf).* FROM (
    SELECT my_func(x) AS mf FROM some_table OFFSET 0
) sub;</code>

3。 CTE(通用表表达式)方法:

<code class="language-sql">WITH tmp(mf) AS (
    SELECT my_func(x) FROM some_table
)
SELECT (mf).* FROM tmp;</code>

4。横向连接(PostgreSQL 9.3 及更高版本):

<code class="language-sql">
SELECT mf.*
FROM some_table
LEFT JOIN LATERAL my_func(some_table.x) AS mf ON true;
```  This is the preferred method for PostgreSQL 9.3 and above.


### Explanation

The root cause lies in how PostgreSQL's parser handles `(func()).*` in older versions.  The wildcard expands into individual column selections, mistakenly causing the function to be called repeatedly for each column.


### Why Repeated Calls Occur

Pre-9.3 PostgreSQL parsers interpret `(func()).*` by replicating nodes within the parse tree.  This replication results in a separate function call for every selected column, even if a single call would suffice.</code>

以上是如何在旧 PostgreSQL 版本中使用 `(func()).*` 防止多个函数调用?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn