如何在SQL(CTE)中查找节点的多个根节点

时间:2014-02-28 14:11:40

标签: sql sql-server recursive-query

我有两张表如下

 Table Person

 Id   Name
 1    A
 2    B
 3    C
 4    D
 5    E

Table RelationHierarchy

 ParentId   CHildId
    2         1
    3         2
    4         3
  This will form a tree like structure

  D
  |
  C
  |
  B
  |
  A

I am using following CTE to find top level parent

DECLARE @childID INT 
SET @childID  = 1 --chield to search

;WITH RCTE AS
 (
  SELECT *, 1 AS Lvl FROM RelationHierarchy 
  WHERE ChildID = @childID

UNION ALL

SELECT rh.*, Lvl+1 AS Lvl FROM dbo.RelationHierarchy rh
INNER JOIN RCTE rc ON rh.CHildId = rc.ParentId
  )
   SELECT TOP 1 id, Name
   FROM RCTE r
  inner JOIN dbo.Person p ON p.id = r.ParentId
  ORDER BY lvl DESC

现在的问题是,如果一个人是多个层次结构的一部分i-e有多个Root ID我怎么能找到它。任何人都可以改变上面提到的代码吗?

0 个答案:

没有答案