如何跟踪表行之间的ID / ParentID关系?

时间:2010-04-27 11:47:08

标签: c# sql sql-server stored-procedures function

我有一个包含此数据的records(ID, ParentID)表:

ID   ParentID  
1    null  
2    1  
3    2   
4    2  
5    3  
6    null  
7    6  

如果您将此表格作为一个系列绘制在层次结构中,1,2,3,4,5将彼此相关。

我想找到一种方法来传递一个ID(比如3),以便它给我其他家庭成员。我正在使用C#和SQL,要么会这样做 - 我想找到这样的结果:

3 - result 1,2,4,5
2 - result 1,3,4,5
6 - result 7
and so on

我想找到我传入的身份证明的父母,祖父母,子女和孙子女(如我的例子所示)。

3 个答案:

答案 0 :(得分:3)

答案 1 :(得分:1)

这应该这样做。

CREATE TABLE #Test
(
    ID int,
    ParentID int
)

INSERT #Test VALUES (1, null)
INSERT #Test VALUES (2, 1)
INSERT #Test VALUES (3, 2)
INSERT #Test VALUES (4, 2)
INSERT #Test VALUES (5, 3)
INSERT #Test VALUES (6, null)
INSERT #Test VALUES (7, 6)

DECLARE @QueryId int
SET @QueryId = 2

-- My parents
SELECT [ParentID] FROM #Test WHERE [ID] = @QueryID AND [ParentID] IS NOT NULL
UNION -- My parent's parents
SELECT [ParentID] FROM #Test WHERE [ID] IN (SELECT [ParentID] FROM #Test WHERE [ID] = @QueryID) AND [ParentID] IS NOT NULL
UNION -- My parent's children (i.e. my siblings), excluding me
SELECT [ID] FROM #Test WHERE [ParentID] IN (SELECT [ParentID] FROM #Test WHERE [ID] = @QueryID) AND [ID] != @QueryID
UNION -- My chidren
SELECT [ID] FROM #Test WHERE [ParentID] = @QueryId
UNION -- My chidren's children
SELECT [ID] FROM #Test WHERE [ParentID] IN (SELECT [ID] FROM #Test WHERE [ParentID] = @QueryId)

DROP TABLE #Test

答案 2 :(得分:0)

您可能需要查看适合您问题的Hierarchy类型。虽然这仅适用于SQL Server 2008