gpt4 book ai didi

获取项目的所有祖先的 SQL 递归查询

转载 作者:行者123 更新时间:2023-12-01 18:34:24 26 4
gpt4 key购买 nike

ID       parent_id   name
---------------------
1 2 first
2 4 second
3 3 third
4 5 fourth
5 - fifth

第一个的祖先列表应该是(2, 4, 5)

最佳答案

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

关于获取项目的所有祖先的 SQL 递归查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16749095/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com