我试图检索特定经理的整个员工层次结构。
表格如下:
id :: int
manager :: foreign key(users)
数据:
| id | manager |
-----------------
| 103 | 138 |
| 125 | 138 |
| 114 | 103 |
| 122 | 103 |
| 138 | NULL |
| 144 | 222 |
| 222 | NULL |
当我执行以下递归时:
WITH RECURSIVE managed AS (
SELECT manager AS manager_id, id AS employee_id
FROM users
WHERE manager = 138
UNION
SELECT u2.manager AS manager_id, u2.id as employee_id
FROM users u2
INNER JOIN managed m ON m.employee_id = u2.id
)
select *
from managed;
我收到了错误的结果:
虽然预期是:(完全如下面的链接显示......)
| employee_id | manager_id |
-----------------------------
| 103 | 138 |
| 125 | 138 |
| 114 | 103 |
| 122 | 103 |
我尝试了很多例子,包括:: this one,这与我的问题相似,但没有一个有效......
当我尝试用UNION ALL
执行查询时,执行永远不会结束(几分钟后我不得不取消执行)
提前致谢:)
答案 0 :(得分:1)
您有小错误 - 您需要加入m.employee_id = u2.manager
而不是m.employee_id = u2.id
:
WITH RECURSIVE managed AS (
SELECT manager AS manager_id, id AS employee_id
FROM users
WHERE manager = 138
UNION
SELECT u2.manager AS manager_id, u2.id as employee_id
FROM users u2
INNER JOIN managed m ON m.employee_id = u2.manager
)
select *
from managed;
结果是:
manager_id | employee_id
------------+-------------
138 | 103
138 | 125
103 | 114
103 | 122
(4 rows)
答案 1 :(得分:0)
以下是查找员工层次结构的方法:
WITH managers AS (
SELECT u.id
FROM users u
WHERE exists (SELECT 1 FROM users WHERE manager = u.id LIMIT 1)
)
SELECT u.id as employee_id, m.id as manager_id
FROM users u
JOIN managers m ON m.id = u.manager;
- >
employee_id | manager_id
-------------+------------
122 | 103
114 | 103
103 | 138
125 | 138
(4 rows)