如何在PostgreSQL(版本10.2)中串联RECURSIVE CTE中的父项列表?
例如,我有:
CREATE TABLE test (
id SERIAL UNIQUE,
parent integer references test(id),
text text NOT NULL
);
具有:
INSERT INTO test(parent, text) VALUES
(NULL, 'first'),
(1, 'second'),
(2, 'third'),
(3, 'fourth'),
(NULL, 'top'),
(5, 'middle'),
(6, 'bottom');
我如何获得带有特定项目的树,并将其所有父级并入(或以数组的形式)给定ID?
到目前为止,我有以下查询以查看返回的内容,但似乎无法添加正确的WHERE子句以返回正确的值:
WITH RECURSIVE mytest(SRC, ID, Parent, Item, Tree, JOINED) AS (
SELECT '1', id, parent, text, array[id], text FROM test
UNION ALL
SELECT '2', test.id, test.parent, test.text as Item, NULL,
concat(t.joined, '/', test.text)
FROM mytest as t
JOIN test ON t.id = test.parent
)
SELECT * FROM mytest;
这给了我整个设置,但是一旦我添加了WHERE id = 1之类的东西,我就没有得到我期望的结果(我正在寻找该项和父项的串联列表)。
答案 0 :(得分:2)
在自上而下方法中,初始查询应仅选择根(不带父项的项目),因此查询仅返回每行一次:
with recursive top_down as (
select id, parent, text
from test
where parent is null
union all
select t.id, t.parent, concat_ws('/', r.text, t.text)
from test t
join top_down r on t.parent = r.id
)
select id, text
from top_down
where id = 4 -- input
如果您的目标是查找特定商品,则自下而上方法会更有效:
with recursive bottom_up as (
select id, parent, text
from test
where id = 4 -- input
union all
select r.id, t.parent, concat_ws('/', t.text, r.text)
from test t
join bottom_up r on r.parent = t.id
)
select id, text
from bottom_up
where parent is null
删除两个查询中的final where条件以查看差异。