Recursive CTE concatenate fields with parents from arbitrary point

我们两清 提交于 2019-12-02 05:46:52

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

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

Test it in rextester.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!