问题
I have a table with hierarchical data in it, the structure goes like this:
ID ParentId
---- ----------
1 NULL
2 1
3 2
4 2
5 3
6 5
If I pass the node Id I would like to get the top most node Id/details by traversing through all its parents in SQL.
I tried CTE, i somehow cannot get the combination correct. However, i got this working as a function but it is so slow that i had to post this question.
In the above example if I pass 6, i would want to have the top most i.e. 1. By traversing through 6 => 5 => 3 => 2 => [1] (result)
Thanks in advance for your help.
回答1:
Please try:
declare @id int=6
;WITH parent AS
(
SELECT id, parentId from tbl WHERE id = @id
UNION ALL
SELECT t.id, t.parentId FROM parent
INNER JOIN tbl t ON t.id = parent.parentid
)
SELECT TOP 1 id FROM parent
order by id asc
回答2:
DECLARE @id INT = 6
;WITH parent AS
(
SELECT id, parentId, 1 AS [level] from tbl WHERE id = @id
UNION ALL
SELECT t.id, t.parentId, [level] + 1 FROM parent
INNER JOIN tbl t ON t.id = parent.parentid
)
SELECT TOP 1 id FROM parent ORDER BY [level] DESC
@TechDo's answer assumes the lowest ID will be the parent. If you don't want to rely on this then the above query will sort by the depth.
回答3:
You can try this query my friend to get all ids:
with tab1(ID,Parent_ID) as
(select * from table1 where id = 6
union all
select t1.* from table1 t1,tab1
where tab1.Parent_ID = t1.ID)
select ID from tab1;
and this query will give the final result:
with tab1(ID,Parent_ID) as
(select * from table1 where id = 6
union all
select t1.* from table1 t1,tab1
where tab1.Parent_ID = t1.ID)
select ID from tab1 where parent_id is null;
SQL Fiddle
回答4:
;WITH CTE
as
(
Select I.ID,P.Parent_id
from #temp I
join #temp P
on P.Id = I.Parent_Id
where i.ID = 6
union all
Select I.ID,P.Parent_id
from CTE I
join #temp P
on P.Id = I.Parent_Id
where p.Parent_Id is not null
)
Select ID,min(parent_id) from CTE group by id;
来源:https://stackoverflow.com/questions/24523560/get-root-parent-of-child-in-hierarchical-table