3

我有一个表值 PL/pgsql 函数,它将一个整数、一个 ID 作为 1 输入。返回的表具有固定列(例如 5),但行数不同。

这些唯一 ID 有一个大表。我想将此函数应用于每个 ID 并 UNION ALL 结果。

在网上看,我一直看到 CROSS APPLY 作为解决方案,但它似乎在 PostgreSQL 中不可用。我该如何做这个“应用”操作?

一个简单的解决方案是用一个额外的外循环重写表值函数。但是有没有办法直接在 SQL 中做到这一点?

4

2 回答 2

2

我认为在当前版本的 PostgreSQL (9.2) 中是不可能的。在 9.3 中会有LATERAL 连接,它完全符合您的要求。

但是,您可以apply返回一组简单值的函数:

select id, func(id) as f from tbl1

sql fiddle demo

于 2013-08-21T15:37:40.670 回答
1

SQL小提琴

create table t (id int);
insert into t (id) select generate_series(1, 10);

create or replace function f (i integer)
returns table(id_2 integer, id_3 integer) as $$
    select id * 2 as id_2, id * 3 as id_3
    from t
    where id between i - 1 and i + 1
$$ language sql;

select id, (f(id)).*
from t;
于 2013-08-21T16:01:16.257 回答