如何垂直连接同一个表

时间:2014-12-05 14:33:30

标签: sql-server-2008 tsql

所以我有一张这样的表:

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

这样做的最佳方式是什么?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

DECLARE @ID INT=3
;with cte as(
select ID,Name,ParentID FROM @Nodes WHERE ID=@ID
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