2014-12-05 73 views
1

所以我有一個表是這樣的:如何垂直加入同一個表

DECLARE @Nodes TABLE (ID INT, Name VARCHAR(100), ParentID INT) 
INSERT INTO @Nodes VALUES 
(1, 'Test', NULL), 
(2, 'Test', 1), 
(3, 'Test', 2), 
(5, 'Test', 3), 
(6, 'Test', 1) 

現在我想查詢該表,檢索與節點ID 3和所有的父節點。 ParentID將是同一個表的ID列的外鍵。可能的父節點的數量是無限的。結果會是這樣的:

ID Name ParentID 
1 Test NULL 
2 Test 1 
3 Test 2 

這樣做的最佳方法是什麼?

回答

1

你可以使用一個recursive common table expression

WITH Nodes 
AS(
    SELECT 1 AS relationLevel, child.* 
    FROM @Nodes child 
    WHERE child.ID = 3 

    UNION ALL 

    SELECT relationLevel+1, parent.* 
    FROM Nodes nextOne 
    INNER JOIN @Nodes parent ON parent.ID = nextOne.ParentID 
) 
SELECT * FROM Nodes order by ID 

DEMO

0
DECLARE @ID INT=3 
;with cte as(
select ID,Name,ParentID FROM @Nodes WHERE [email protected] 
UNION ALL 
SELECT n.ID,n.Name,n.ParentID FROM cte inner join @Nodes n on cte.ParentID= n.ID 
) 
SELECT ID,Name,ParentID FROM cte 
ORDER BY ParentID