Postgres 9.3 或更高版本
使用LATERAL
加入!
SELECT p.id, p.name, p.data, f.*
FROM tb_projects p
LEFT JOIN LATERAL fn_getlinkedproject(p.id) f(linked_id, lined_name) ON TRUE;
结果:
id | data | name | linked_id | linked_name
----+--------+--------+-----------+-------------
1 | data_1 | name_1 | 2 | name_2
2 | data_2 | name_2 | 3 | name_3
3 | data_3 | name_3 | 1 | name_1
看:
Postgres 9.2 或更高版本
劣质有几个原因。附加列别名并不那么简单。而是重命名其他冲突的名称:
SELECT p.id AS p_id, p.data AS p_data, p.name AS p_name, (fn_getlinkedproject(p.id)).*
FROM tb_projects p;
结果:
p_id | p_data | p_name | id | name
------+--------+--------+----+--------
1 | data_1 | name_1 | 2 | name_2
2 | data_2 | name_2 | 3 | name_3
3 | data_3 | name_3 | 1 | name_1
要重命名结果列,您必须:
SELECT p.id, p.data, p.name
,(fn_getlinkedproject(p.id)).id AS linked_id
,(fn_getlinkedproject(p.id)).name AS linked_name
FROM tb_projects p;
两种旧的解决方案都解决了重复调用该函数的相同(不良)查询计划。
为避免这种情况,请使用子查询:
SELECT p.id, p.data, p.name
, (p.x).id AS linked_id, (p.x).name AS linked_name
FROM (SELECT *, fn_getlinkedproject(id) AS x FROM tb_projects) p;
注意必要括号的位置。
阅读有关复合类型的手册。
演示
CREATE TYPE dm_nameid AS (
id int
, name text); -- types simplified for demo
CREATE TABLE tb_projects(
id int
, data text
, name text);
INSERT INTO tb_projects VALUES
(1, 'data_1', 'name_1')
, (2, 'data_2', 'name_2')
, (3, 'data_3', 'name_3');
CREATE function fn_getlinkedproject(integer) -- avoiding CaMeL-case for demo
RETURNS dm_nameid LANGUAGE sql AS
'SELECT id, name FROM tb_projects WHERE id = ($1 % 3) + 1';
db<>在这里摆弄