如何在返回表中查找父级ID

4

I have following table:

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

我想要找到特定子ID的第一个ID。 例如:ID=7,结果为1
ID=6,结果为4。
如何做到这一点?
2个回答

4
你需要使用递归CTE的技巧来解决这个问题。
给定一个表变量的数据如下:
declare @data table(id int, parentid int)
insert into @data
  select 1, null
  union select 2,1
  union select 3,2
  union select 4, null
  union select 5,4
  union select 6,5
  union select 7,3

以下方法可以解决问题:
;with recursiveTable as
(
    select d.id, d.parentId, 0 as depth
    from @data d
    where d.id=6 -- Parameterize this
    union all

    select d.id, d.parentid, r.depth-1
    from @data d
    inner join recursiveTable r
    on d.id = r.parentId
)
select top 1 id 
from recursiveTable 
order by depth

将数字 6 插入如上所述,返回的结果是 4。将其更改为 7,即可按照要求返回 1

1
因为那会太简单了。 ;) 谈论过度思考解决方案,回答已更新,谢谢! - Jamiec

0

试试这个:

 CREATE TABLE childpar(ID int,ParentID int)
    INSERT INTO childpar 
    values(1,NULL),
    (2, 1),
    (3, 2),
    (4, NULL),
    (5, 4),
    (6, 5),
    (7, 3)


DECLARE @inpyID int
SET @inpyID=7

;WITH CTE1 as (
select * from childpar where id=@inpyID
union all
select c2.* from CTE1 c1 inner join childpar c2 on c1.ParentID = c2.ID
)

select top 1 id from CTE1 order by id asc

我不明白这里第一个CTE的意义,并且还依赖于父级ID低于子级ID。虽然对于OP来说是这样,但我认为你不能总是做出这样的假设! - Jamiec
仍然受到我上面提到的第二点的影响。你依赖于id的顺序。 - Jamiec
你是在谈论这个语句 "select top 1 id from CTE1 order by id asc" 吗? - AnandPhadke

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接