0

我有以下数据库架构

位置表

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,查询返回元素的所有子元素。

4

2 回答 2

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 小提琴演示

于 2013-09-26T07:37:48.637 回答
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
于 2013-09-26T08:47:53.377 回答