递归CTE从任意点将字段与父级连接 [英] Recursive CTE concatenate fields with parents from arbitrary point

查看:69
本文介绍了递归CTE从任意点将字段与父级连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在PostgreSQL(版本10.2)中串联RECURSIVE CTE中的父项列表?

How can I concatenate a list of parent items in a RECURSIVE CTE with PostgreSQL (version 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');

我如何获得带有特定项目的树,并将其所有父级并入(或以数组的形式)给定其ID?

How do I get a tree with a particular item and all it's parents concatenated (or in an array) given it's id?

到目前为止,我有以下查询以查看返回的内容,但似乎无法添加正确的WHERE子句以返回正确的值:

So far I have the following query to see what is being returned, but I can't seem to add the right WHERE clause to return the right value:

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

This gives me the entire set but as soon as I add something like WHERE id = 1 I don't get the results I expect (I'm looking for a concatenated list of the item and parents).

推荐答案

自顶向下方法中,初始查询应仅选择根(不带父项的项目),因此查询仅返回每行一次:

In the top-down method the initial query should select only roots (items without parents), so the query returns each row only once:

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

如果您的目标是找到特定的商品,则自下而上的方法会更有效:

If your goal is to find a specific item, the bottom-up approach is more efficient:

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条件,以查看差异.

Remove final where conditions in both queries to see the difference.

在rextester中对其进行测试.

这篇关于递归CTE从任意点将字段与父级连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆