Postgresql递归返回意外结果

时间:2017-03-13 18:15:53

标签: sql postgresql recursion postgresql-9.5

我试图检索特定经理的整个员工层次结构。

表格如下:

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;

我收到了错误的结果:

enter image description here

虽然预期是:(完全如下面的链接显示......)

| employee_id  | manager_id | 
-----------------------------
| 103          | 138        |
| 125          | 138        |
| 114          | 103        |
| 122          | 103        |

我尝试了很多例子,包括:: this one,这与我的问题相似,但没有一个有效......

当我尝试用UNION ALL执行查询时,执行永远不会结束(几分钟后我不得不取消执行)

提前致谢:)

2 个答案:

答案 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)