9.3及以上:横向查询
在 PostgreSQL 9.3 或更新版本中使用隐式横向查询:
SELECT f.* FROM things t, some_function(t.thing_id) f;
对于所有新查询,首选此公式。以上是标准制定。
它也适用于 RETURNS TABLE 或 RETURNS SETOF RECORD 的函数以及带有 RETURNS RECORD 的输出参数的函数。
它是以下的简写:
SELECT f.*
FROM things t
CROSS JOIN LATERAL some_function(t.thing_id) f;
9.3 之前:通配符扩展(小心)
以前的版本,导致some_function 的多重评估,如果some_function 返回一个集合,不工作,不要使用这个:
SELECT (some_function(thing_id)).* FROM things;
以前的版本,避免使用第二层间接对some_function 进行多重评估。仅当您必须支持相当旧的 PostgreSQL 版本时才使用它。
SELECT (f).*
FROM (
SELECT some_function(thing_id) f
FROM things
) sub(f);
演示:
设置:
CREATE FUNCTION some_function(i IN integer, x OUT integer, y OUT text, z OUT text) RETURNS record LANGUAGE plpgsql AS $$
BEGIN
RAISE NOTICE 'evaluated with %',i;
x := i;
y := i::text;
z := 'dummy';
RETURN;
END;
$$;
create table things(thing_id integer);
insert into things(thing_id) values (1),(2),(3);
试运行:
demo=> SELECT f.* FROM things t, some_function(t.thing_id) f;
NOTICE: evaluated with 1
NOTICE: evaluated with 2
NOTICE: evaluated with 3
x | y | z
---+---+-------
1 | 1 | dummy
2 | 2 | dummy
3 | 3 | dummy
(3 rows)
demo=> SELECT (some_function(thing_id)).* FROM things;
NOTICE: evaluated with 1
NOTICE: evaluated with 1
NOTICE: evaluated with 1
NOTICE: evaluated with 2
NOTICE: evaluated with 2
NOTICE: evaluated with 2
NOTICE: evaluated with 3
NOTICE: evaluated with 3
NOTICE: evaluated with 3
x | y | z
---+---+-------
1 | 1 | dummy
2 | 2 | dummy
3 | 3 | dummy
(3 rows)
demo=> SELECT (f).*
FROM (
SELECT some_function(thing_id) f
FROM things
) sub(f);
NOTICE: evaluated with 1
NOTICE: evaluated with 2
NOTICE: evaluated with 3
x | y | z
---+---+-------
1 | 1 | dummy
2 | 2 | dummy
3 | 3 | dummy
(3 rows)