4

邻接列表表中,给定节点的 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
4

3 回答 3

2

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

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
于 2013-08-28T08:00:30.687 回答
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

(从SQL SERVER 中 ORACLE 的 CONNECT BY PRIOR 模拟修改的答案)

于 2012-11-08T18:32:54.303 回答
0

这是带有 WHILE 循环的代码。适用于表中的多棵树:

declare @current_node int
declare @parent_node int
declare @MAX_ITERATIONS int
declare @count int

SET @current_node=@id -- node to start with
SET @MAX_ITERATIONS = 100 --maximum iterations count
SET @count=0 


while(@count<@MAX_ITERATIONS) -- to prevent endless loop  
begin
 select @parent_node=parentid from tree where id=@current_node
 if @parent_node is null -- root is found
  begin 
    break; 
  end
 set @current_node=@parent_node 
 SET @count=@count+1
end

if (@count=@MAX_ITERATIONS) SET @current_node=NULL --if it was endless loop

select @current_node; -- output root id
于 2012-07-27T12:47:16.850 回答