Recursive CTE concatenate fields with parents from arbitrary point

前端 未结 1 1865
心在旅途
心在旅途 2020-12-21 14:17

How can I concatenate a list of parent items in a RECURSIVE CTE with PostgreSQL (version 10.2)?

For example, I have:

CREATE TABLE test (
    id SERIA         


        
相关标签:
1条回答
  • 2020-12-21 14:28

    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.

    0 讨论(0)
提交回复
热议问题