【发布时间】:2020-04-08 14:04:10
【问题描述】:
我想在 Postgres 中的单个表上创建一个 RECURSIVE 查询,它基本上是基于父和子的。
这是带有数据的演示表员工
id parentid managerid status
------------------------------------
3741 [null] 1709 7
3742 3741 1709 12
3749 3742 1709 12
3900 3749 1709 4
1) 如果 Status = 12 那么结果将是具有 status = 12 的数据以及该特定的所有 父母节点。
预期结果将是:
id parentid managerid status
--------------------------------------
3741 [null] 1709 7
3742 3741 1709 12
3749 3742 1709 12
为此,我已经尝试过下面给出的查询工作正常并给出正确的结果,即使我更改了状态值而不是它的工作正常。
WITH RECURSIVE nodes AS (
SELECT s1.id, case when s1.parentid=s1.id then null else s1.parentid end parentid,s1.managerid, s1.status
FROM employees s1 WHERE id IN
(SELECT employees.id FROM employees WHERE
"employees"."status" = 12 AND "employees"."managerid" = 1709)
UNION ALL
SELECT s2.id, case when s2.parentid=s2.id then null else s2.parentid end parentid,s2.managerid, s2.status
FROM employees s2 JOIN nodes ON s2.id = nodes.parentid
)
SELECT distinct nodes.id, nodes.parentid, nodes.managerid, nodes.status
FROM nodes ORDER BY nodes.id ASC NULLS FIRST;
2) 如果 Status != 12 那么结果将是,只有该特定节点的所有 父母。
预期结果将是:
id parentid managerid status
--------------------------------------
3741 [null] 1709 7
我希望查询状态不等于某个值。
【问题讨论】:
标签: postgresql recursive-query