Sql server 如何在返回表中查找父ID
我有以下表格:Sql server 如何在返回表中查找父ID,sql-server,sql-server-2008,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
ID ParentID
1 NULL
2 1
3 2
4 NULL
5 4
6 5
7 3
我要查找特定子ID的第一个ID。
示例:ID=7,结果为1ID=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
。尝试以下操作:
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比孩子低。虽然这是OP的情况,但我不认为你可以假设它总是如此!仍然受到我上面第二点的困扰。你是在依赖id的顺序你是在说“按id从CTE1顺序中选择前1个id asc”语句吗?