在单个 table 上对 Postgres 进行递归查询

RECURSIVE query for Postgres on a single table

我想在 Postgres 中的单个 table 上创建一个 RECURSIVE 查询,它基本上基于父子关系。

这是演示table员工数据

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 和所有 parents 该特定节点。

预期结果将是:

 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 那么结果将是,只有那个特定节点的所有 parents

预期结果将是:

 id     parentid   managerid   status
--------------------------------------
 3741   [null]      1709        7    

我希望状态查询不等于某个值。

这是一个非常简单的解决方案,但我认为它应该适用于较小的数据集

  SELECT * FROM employee
  WHERE 
    status=12
    OR id IN (
      SELECT DISTINCT parentId FROM employee WHERE status=12
    )
`

使用此递归 CTE:

with recursive cte as (
  select * from tablename
  where status = 12
  union all
  select t.* 
  from tablename t inner join cte c
  on c.parentid = t.id
)
select distinct * from cte;

参见demo
结果:

| id   | parentid | managerid | status |
| ---- | -------- | --------- | ------ |
| 3741 |          | 1709      | 7      |
| 3742 | 3741     | 1709      | 12     |
| 3749 | 3742     | 1709      | 12     |
WITH RECURSIVE CTE AS
(
 SELECT *
 FROM tablename
 WHERE status = 12
 UNION
 SELECT t.*
 FROM tablename t
 INNER JOIN cte c ON c.Id = t.parentid
)
SELECT t.*
FROM tablename t
LEFT JOIN cte c on t.id=c.id
WHERE c.id IS NULL
ORDER BY id ASC NULLS FIRST;
WITH RECURSIVE cte AS (
  SELECT * FROM tablename
  WHERE status != 12
  UNION
  SELECT t.* 
  FROM tablename t INNER JOIN cte c
  ON c.parentid = t.id
)
SELECT DISTINCT * FROM cte;

更多参考演示:demo