父子T-SQL查询

时间:2013-09-26 07:23:12

标签: sql-server performance tsql parent-child

我有以下数据库架构

位置表

LocationID   LocationName
1         |   L1
2         |   L2
.         |   L3
.         |   L4
.         |   L5  
n         |   Ln

和另一个定义父子关系和模式的表是

ID    LocationID    ParentID
1       1            null
2       2            1
3       3            1
4       4            2

等等。

我想在任何级别传递元素的ID或多个ID,查询将返回元素的所有子元素。

2 个答案:

答案 0 :(得分:1)

select l.LocationID,l.LocationName,m.LocationID AS Child,l1.LocationName AS ChildName
from Location l
inner join mappingtable m
ON l.LocationID=m.ParentID
inner join Location l1
ON l1.LocationID=m.LocationID

SQL FIDDLE DEMO

答案 1 :(得分:1)

declare @relation table(ID int, LocationID int, ParentID int)
insert @relation values
(1,1,null),(2,2,1),(3,3,1),(4,4,2)

declare @Location table (LocationID int,    LocationName varchar(3))
insert @Location values
(1,'L1'),(2,'L2'),(3,'L3'),(4,'L4'),(5,'L5'),(6,'L6')

;with a as
(
select ID p, ID, LocationID, ParentID from @relation where parentid is null
union all
select a.p, t.ID, t.LocationID, t.ParentID
from a join @relation t
on a.ID = t.ParentID
)
select L1.LocationID ParentID, L1.LocationName ParentName, L2.LocationID, L2.LocationName  from a
join @Location L1
on a.p = L1.LocationID
join @Location L2
on a.id = L2.LocationID
option (maxrecursion 500)

结果:

ParentID  ParentName LocationID LocationName
1         L1         1          L1
1         L1         2          L2
1         L1         3          L3
1         L1         4          L4