1

举个例子:

返回表的函数:

=> create or replace function testf(x integer)
     returns table(a integer, b integer)
   language sql
   as $function$
       select * from (values(1,2)) as foo(a,b)
   $function$;

调用它以便它返回一条记录(或任何你称之为的):

=> select testf(3);
 testf
-------
 (1,2)

调用它使其返回一个表(好):

=> select * from  testf(3);
 a | b
---+---
 1 | 2

但是我该如何调用它,以便参数来自查询?

=> select s.n, testf(s.n) from (select 3 as n union select 4) s;
 n | testf
---+-------
 3 | (1,2)
 4 | (1,2)            <-- not a table (or row with column names)


=> select * from  testf(s.n) from (select 3 as n) s;
 ERROR:  syntax error at or near "from"
 LINE 1: select * from  testf(s.n) from (select 3 as n) s;
4

1 回答 1

2

使用LATERAL子查询:

SELECT *
FROM  (VALUES (3), (4)) AS s(n)
     , testf(s.n);

逗号是 的缩写CROSS JOIN LATERAL,因为在子句LATERAL中使用集合返回函数自动假定。FROM

有关的:

于 2017-01-27T14:16:38.203 回答