gpt4 book ai didi

sql - 在邻接表中查找后代的根节点

转载 作者:行者123 更新时间:2023-12-01 04:03:16 24 4
gpt4 key购买 nike

邻接表表,给定一个节点的 id,我怎么能找到它的关联 根节点 ?

笔记:

该表包含多棵树,因此我不能简单地搜索空 parentId。

更多信息:

这是我目前所拥有的,有什么问题或改进吗?

with tree as
(
select
t.*

from table1 t
where t.id = @id

union all

select
t2.*

from tree
join table1 t2 on tree.parentId = t2.id
)

select *
from tree
where parentId is null

最佳答案

我不认为提供的任何解决方案比我自己的更好,所以我最终选择了这个:

with tree as
(
select
t.*

from table1 t
where t.id = @id

union all

select
t2.*

from tree
join table1 t2 on tree.parentId = t2.id
)

select *
from tree
where parentId is null

关于sql - 在邻接表中查找后代的根节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11646409/

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