我有以下2个表格:
CREATE TABLE [Names]
(
[Id] INT PRIMARY KEY,
[Name] VARCHAR(100)
)
CREATE TABLE [Relationships]
(
[Parent] [int] REFERENCES [Names]([Id]),
[Child] [int] REFERENCES [Names]([Id])
)
Sample Data:
INSERT [NAMES] VALUES (1,'FRANK')
INSERT [NAMES] VALUES (2,'JO')
INSERT [NAMES] VALUES (3,'MARY')
INSERT [NAMES] VALUES (4,'PETER')
INSERT [NAMES] VALUES (5,'MAY')
INSERT [RELATIONSHIPS] VALUES (1,2)
INSERT [RELATIONSHIPS] VALUES (2,3)
INSERT [RELATIONSHIPS] VALUES (4,2)
INSERT [RELATIONSHIPS] VALUES (5,4)
如何显示嵌套(树)名称列表,包括[Id],[Name]和[Level],其中[Level]表示从顶部开始的嵌套级别(Root:Level = 0; Root的第一个子级:等级= 1;等等......)? 例如,结果应显示:
Level Relationship
----- ------------
2 FRANK <- JO
3 FRANK <- JO <- MARY
2 PETER <- JO
3 MAY <- PETER <- JO
答案 0 :(得分:0)
您可以考虑切换到Hierarchical Data。 TSQL支持它很好,你不需要重新发明轮子&#39;。从长远来看,这将使您的查询更容易。
答案 1 :(得分:0)
试试这个:
with Relatives as
(
select n.Id, cast(n.Name as varchar(max)) Relationship, 0 [Level]
from Names n
where not exists
(
select *
from Relationships r
where n.Id = r.Child
)
union all
select n.Id, p.Relationship + ' <- ' + n.Name Relationship, p.[Level] + 1 [Level]
from Names n
join Relationships r
on n.Id = r.Child
join Relatives p
on r.Parent = p.Id
)
select Relationship, [Level]
from Relatives