[英]How can I make recursive query in SQL?
我有像這樣的拖車桌
用戶
id | name
_______________
1 | one
2 | two
3 | three
4 | four
5 | five
6 | six
雇員
id | userId | reportedTo
_________________________
1 | 1 | null
2 | 2 | 1
3 | 3 | 2
4 | 4 | 3
5 | 5 | 4
6 | 6 | 5
我需要類似的東西
如果我為某個用戶運行查詢,那么它將返回所有報告的記錄是這個用戶和其他用戶報告的記錄是報告給這個用戶
喜歡:
如果我為用戶 1 運行此查詢,那么它將返回所有記錄,接受員工的 userId 1
id | userId | reportedTo
_________________________
2 | 2 | 1
3 | 3 | 2
4 | 4 | 3
5 | 5 | 4
6 | 6 | 5
如果我對 userId 4 運行查詢,那么它將從員工表中返回 userId 5 和 6 的記錄
id | userId | reportedTo
_________________________
5 | 5 | 4
6 | 6 | 5
誰能幫我這個。
提前致謝
您可以使用遞歸 CTE:
with recursive cte(i, u, r) as (
select * from employees where reportedTo = 1
union all
select e.* from cte c join employees e on c.u = e.reportedTo
)
select c.i id, c.u userId, c.r reportedTo from cte c;
Output:
ID | 用戶身份 | 報告給 |
---|---|---|
2 | 2 | 1 |
3 | 3 | 2 |
4 | 4 | 3 |
5 | 5 | 4 |
6 | 6 | 5 |
看演示
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.