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

时间:2012-07-25 09:13:31

标签: sql sql-server tree root adjacency-list

邻接列表表中,给定节点的ID,如何找到与之关联的根节点

注意:

该表包含多个树,因此我无法简单地搜索null 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

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

这个解决方案对我来说效果很好。不能肯定地说,如果表现比你的更快。

declare @base_id as int;
set @base_id = 1;
WITH n(id) AS 
   (SELECT id 
    FROM table
    WHERE id = @base_id
        UNION ALL
    SELECT nplus1.ID
    FROM table as nplus1, n
    WHERE n.id = nplus1.ParentID)
SELECT id FROM n

(自Simulation of CONNECT BY PRIOR of ORACLE in SQL SERVER修改后的答案)