SQL recursive query that gets all ancestors of an item

后端 未结 2 594
小蘑菇
小蘑菇 2020-12-07 20:53
ID       parent_id   name
---------------------
1        2            first 
2        4            second
3        3            third
4        5            fourth
5          


        
2条回答
  •  一个人的身影
    2020-12-07 21:46

    with name_tree as (
       select id, parent_id, name
       from the_unknown_table
       where id = 1 -- this is the starting point you want in your recursion
       union all
       select c.id, c.parent_id, c.name
       from the_unknown_table c
         join name_tree p on p.parent_id = c.id  -- this is the recursion
    ) 
    select *
    from name_tree
    where id <> 1; -- exclude the starting point from the overall result
    

    SQLFiddle: http://sqlfiddle.com/#!3/87d0c/1

提交回复
热议问题