我有像这样的桌子
使用者
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;
输出:
ID | 用户身份 | 报告到 |
---|---|---|
2 | 2 | 1个 |
3 | 3 | 2 |
4 | 4 | 3 |
5 | 5 | 4 |
6 | 6 | 5 |
观看演示
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句