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

これが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 に答える
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

SQLSERVERでのORACLEのCONNECTBY PRIORのシミュレーションから変更された回答)

于 2012-11-08T18:32:54.303 に答える