我上拿表父子關係如何顯示父ID爲自己和孩子用T-SQL遞歸查詢
ID | ParentID | description
1 | null | Company
2 | 1 | Department
3 | 2 | Unit1
4 | 2 | Unit2
5 | 4 | Unit3
6 | 4 | Unit4
,並假設顯示以下結果遞歸查詢的工作:
ID | ParentID | description
1 | null | Company
2 | 2 | Department
3 | 2 | Unit1
4 | 2 | Unit2
5 | 2 | Unit3
6 | 2 | Unit4
當然,部件和單位的數量更大。基本任務是顯示parentId父級及其子級別。你有什麼想法如何實現這一目標?
到目前爲止,我只發此查詢
WITH cte (ID, ParentID, description)
AS
(
SELECT ID, ParentID, description
FROM T1
UNION ALL
SELECT e.ID, e.ParentID, e.description
FROM T2 AS e
JOIN cte ON e.ID = cte.ParentID
)
SELECT
cte.ID, cte.ParentID, cte.description
FROM cte
cte.ParentID is not null
試着把它放在SQL小提琴上。 –