【问题标题】:Finding the root node of a descendant in an Adjacency List在邻接列表中查找后代的根节点
【发布时间】:2012-07-25 09:13:30
【问题描述】:

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

【问题讨论】:

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


    【解决方案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
    

    【讨论】:

      【解决方案2】:

      这是带有 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
      

      【讨论】:

        【解决方案3】:

        这个解决方案对我来说效果很好。不能肯定地说性能是否比你的快。

        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

        【讨论】:

        • 谢谢。但是我不确定它是否回答了这个问题。除非我做错了什么,否则它似乎会返回子树中每个节点的 ID。
        • 哦,是的,对不起。我误读了这个问题......当我有空闲时间时,看看我是否可以修改我的答案
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-09
        • 1970-01-01
        • 2014-05-21
        • 2014-02-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多