【问题标题】:Get Parent and grand parents of a particular child获取特定孩子的父母和祖父母
【发布时间】:2015-08-30 19:47:55
【问题描述】:

我有如下表

表名:ExampleTable

ChildID       ChildCommonID   ParentID


1               2                0

2               3                0

3               4                1

4               5                3

5               6                4

问题是:

我有一个孩子 id 示例:ChildID= 5

所以我需要检查它是否有父母是否包含父母 然后检查对应的parentid,在这种情况下parentID是4所以需要检查 孩子 4 有任何父母,在这种情况下孩子 4 的 parentID 是 3,所以获取检查孩子 3 有任何父母 在这种情况下,孩子 3 有父母 1,所以在这里检查孩子 1 有没有父母孩子 1 是最高的祖父母,它没有父母,所以停止这个过程 并返回所有子 ID 最多 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。也不需要左连接
  • @ughai 让我试试
  • @RoyiNamir 我希望你作为重复提供的问题是不同的,这个问题只需要最高父级,这里我需要总层次
  • @ArunprasanthKV 删除了副本。
  • @RoyiNamir 感谢您的帮助。如果可以,请帮助我解决我的问题

标签: sql-server sql-server-2005 common-table-expression


【解决方案1】:

就像我的评论一样,您的列在加入时不正确。使用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

【讨论】:

  • 嘿谢谢伙计,愚蠢的错误,但它杀死了我的 1 小时,您的解决方案运行良好。谢谢
  • 我希望 OP 不会将顶部叶子表示为 0 -> 0,因为添加 (0, 2, 0); 会使查询崩溃
  • @RoyiNamir childid 不会为 0,所以我认为查询是安全的,是吗??
  • @ArunprasanthKV 只要孩子 id != parentID ,是的。
  • @RoyiNamir 是的,childid = parentid 不会出现
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多