sql-server - 如何在返回表中查找父 ID

标签 sql-server sql-server-2008

我有下表:

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

我想查找特定子 ID 的第一个 ID。 示例:ID=7,结果为1
ID=6,结果为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

关于sql-server - 如何在返回表中查找父 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11844987/

相关文章:

java - JPA 未加载延迟提取集合的问题

sql - 全文超时异常

SQL获取电话号码序列

.net - 尝试调试 .NET 代码调用的 SQL 存储过程时出现 "The breakpoint will not currently be hit..."错误

sql-server - SSDT "Smart Defaults"按类型划分的值

mysql - SQL根据某些条件将3个表中的数据合并到第4个表中

sql - 根据当前行和下一行对行求和

c# - SQL Server返回给C#的是什么

sql - OR 语句 SQL 的优先级

sql - 转换为 mm/dd/yyyy 格式