我在stackoverflow本身 (Question before)中已经回答了问题。所以我只是因为一个根元素
而重复了一些变化和麻烦的问题我有一个像这样的SQL表
ID Name ParentID
------------------------------
0 Users NULL
1 Alex 0
2 John 0
3 Don 1
4 Philip 2
5 Shiva 2
6 San 3
7 Antony 6
8 Mathew 2
9 Cyril 8
10 Johan 9
-------------------------
我正在寻找像这样的外线
如果我传递ID 7,10,1
输出表将是
ID Name Relation
------------------------------------
7 Antony Alex->Don->San->Antony
10 Johan John->Mathew->Cyril->Johan
1 Alex -
从上面的回答我要强调的是它不应该考虑ID为0且parentid为null的最顶层节点用户。因此对于ID 1,它只返回一个空字符串表示关系或只是连字符( - ) 如何使用CTE
实现这一目标答案 0 :(得分:1)
基于prev answer:
DECLARE @t table (ID int not null, Name varchar(19) not null, ParentID int null)
insert into @t(ID,Name,ParentID) values
(1 ,'Alex',null),
(2 ,'John',null),
(3 ,'Don',1),
(4 ,'Philip',2),
(5 ,'Shiva',2),
(6 ,'San',3),
(7 ,'Antony',6),
(8 ,'Mathew',2),
(9 ,'Cyril',8),
(10,'Johan',9)
declare @search table (ID int not null)
insert into @search (ID) values (7),(10), (1);
;With Paths as (
select s.ID as RootID,t.ID,t.ParentID,t.Name
, CASE WHEN t.ParentId IS NULL THEN '-'
ELSE CONVERT(varchar(max),t.Name) END as Path
from @search s
join @t t
on s.ID = t.ID
union all
select p.RootID,t.ID,t.ParentID,p.Name, t.Name + '->' + p.Path
from Paths p
join @t t
on p.ParentID = t.ID
)
select *
from Paths
where ParentID is null;
<强> Rextester Demo 强>
答案 1 :(得分:0)
根据您的架构和数据,此查询:
with P as
(
select *, cast(null as nvarchar) as chain from People where parentID is null
union all
select C.*, cast(coalesce(P.chain, P.name) + '->' + C.name as nvarchar)
from People C inner join P on C.parentID = P.id
)
select id, name, coalesce(chain, '-') relation from P where id in (7, 10, 1)
收率:
id name relation
----- ------ ------------------------------
1 Alex -
10 Johan John->Mathew->Cyril->Johan
7 Antony Alex->Don->San->Antony