-
StackOverflow 文件
-
SQL 教程
-
常用表格表示式
-
遞迴列舉子樹
WITH RECURSIVE ManagedByJames(Level, ID, FName, LName) AS (
-- start with this row
SELECT 1, ID, FName, LName
FROM Employees
WHERE ID = 1
UNION ALL
-- get employees that have any of the previously selected rows as manager
SELECT ManagedByJames.Level + 1,
Employees.ID,
Employees.FName,
Employees.LName
FROM Employees
JOIN ManagedByJames
ON Employees.ManagerID = ManagedByJames.ID
ORDER BY 1 DESC -- depth-first search
)
SELECT * FROM ManagedByJames;
水平 |
ID |
FName 引數 |
LName |
1 |
1 |
詹姆士 |
工匠 |
2 |
2 |
約翰 |
約翰遜 |
3 |
4 |
喬納森 |
工匠 |
2 |
3 |
邁克爾 |
威廉姆斯 |