2013-09-26 70 views
0

我有以下DB模式親子T-SQL查詢

位置表

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

+0

似乎是[遞歸的CTE(http://stackoverflow.com/questions/13933255/recursive-sql-的情況下服務器查詢) – cdoubleplusgood

+0

是的。它應該是一個遞歸的CTE。 –

+0

你需要所有級別的所有孩子還是隻有直系後代?因爲在第二種情況下,我認爲你不需要使用CTE。 – DrCopyPaste

回答

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

+0

感謝您的回覆,但這將如何返回我正在尋找的結果? –

+0

對不起,誤解了這個問題。更新了答案。你在找什麼? – dcp1986

+0

感謝您的信息。是否可以提供Id或Id以便我可以在任何級別找到元素的子元素。因此,如果我傳入最頂級的根ID,那麼如果我傳入一個元素的ID,則它將爲我提供所有子元素3它給我的孩子在4級等等? –

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