获得特定 child 的 Parent 和 grand parents

Get Parent and grand parents of a particular child

我有 table 如下

table姓名:ExampleTable

ChildID       ChildCommonID   ParentID


1               2                0

2               3                0

3               4                1

4               5                3

5               6                4

问题是:

我有一个 child id 示例:ChildID= 5

所以我需要检查它是否有 parent 是否包含 parent 然后检查相应的parentid,在这种情况下parentID是4所以需要检查 child 4 有任何 parent ,在这种情况下 parentID child 4 是 3,所以增益检查 child 3 有任何 parent 在这种情况下 child 3 有 parent 1,所以检查 child 1 有任何 parent 在这里 child 1 是顶级盛大 parent 和它没有 parent 所以停止这个过程 并且 return 所有 childid 最多 1

这里的预期输出是

ChildID

5
4
3
1

我曾尝试过类似下面的方法,但它没有给出正确的输出

with getallparent as (
   select * 
   from ExampleTable 
   where ChildID  = 5 
  union all 
  select *
   from ExampleTable c 
     Left join getallparent p on p.ChildID = c.ParentID 
) 
select *
from getallparent;

如果您需要示例数据,可以使用以下查询

create table ExampleTable(ChildID int,ChildCommonID int ,ParentID int )
insert into ExampleTable values(1,2,0)
insert into ExampleTable values(2,3,0)
insert into ExampleTable values(3,4,1)
insert into ExampleTable values(4,5,3)
insert into ExampleTable values(5,6,4)

任何帮助将不胜感激

就像我的评论一样,您的列在连接中不正确。使用 getallparent p on p.ParentID = c.ChildID.

with getallparent as (
   select ChildID,ParentID
   from ExampleTable 
   where ChildID  = 5 
  union all 
  select C.ChildID,C.ParentID
   from ExampleTable c 
     inner join getallparent p on p.ParentID = c.ChildID 
) 
select *
from getallparent;

Fiddle