查询以获取层次表中父级的所有子级

时间:2021-04-06 13:37:12

标签: sql sql-server

我的表结构如下

<头>
ChildId ParentId
1 3
2 3
3 4
4 null

输出必须显示父级所有级别的子级

<头>
ParentId ChildId
4 4
4 1
4 2
4 3
3 3
3 1
3 2
2 2
1 1

因此对于每个父查询都必须显示所有子项,以便如果我们在 where 子句中指定任何单个父项,我们可以获得其所有级别的子项。如果我们也能显示等级就更好了。

我尝试使用递归 CTE 但无法实现所需的输出

2 个答案:

答案 0 :(得分:1)

你有一个奇怪的要求。除了遍历层次结构之外,您还希望所有节点都与自己配对。这不是原始数据的一部分,但可以单独添加:

with cte as (
      select parentId, childid
      from t
      where parentid is not null
      union all
      select cte.parentId, t.childid
      from cte join
           t
           on t.parentId = cte.childId
     )
select *
from cte
union all
select childid, childid
from t;

Here 是一个 db<>fiddle。

答案 1 :(得分:0)

不确定为什么要在层次结构之外添加额外的条目,但您可以像这样设置级别..

declare @T table (
    id        integer identity(1,1) primary key,
    ChildId   Integer,
    ParentId  Integer
)

insert @T (ChildId, Parentid)
      select 4,null
union select 3,4
union select 2,3
union select 1,3

;WITH CTE (ParentId, ChildId, Lvl) AS (
    SELECT ParentId, ChildId, 1
      FROM @T 
     WHERE ParentId IS NULL
UNION ALL
    SELECT T.ParentId, T.ChildId, Lvl + 1
      FROM @T T JOIN CTE E ON E.ChildId = T.ParentId
)
SELECT ChildId,ParentId,Lvl
  FROM CTE
 ORDER BY Lvl