递归 CTE 从任意点将字段与 parents 连接起来

Recursive CTE concatenate fields with parents from arbitrary point

如何将递归 CTE 中的 parent 项列表与 PostgreSQL(版本 10.2)连接起来?

比如我有:

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');

如何获得包含特定项目的树以及所有 parents 连接(或在数组中)给定它的 id?

到目前为止,我有以下查询来查看正在 return 编辑的内容,但我似乎无法将正确的 WHERE 子句添加到 return 正确的值:

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 之类的东西,我就没有得到我期望的结果(我正在寻找项目的串联列表和 parent s).

top-down 方法中初始查询应该 select 只有根(没有父项的项目),所以查询 returns 每行只一次:

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

删除两个查询中的最终 where 条件以查看差异。

Test it in rextester.