Postgres 查询以获取所有子 ID

Postgres query to get all the children ids

我是一个 SQL 菜鸟,到目前为止只写了非常基本的查询。

我有一个 table 看起来像这样

item_full_name      varchar(65535)
item_id             bigint
item_owners         varchar(255)
item_approver_group varchar(255)
item_state          varchar(255)
item_parent_id      bigint
item_children       varchar(65535)

最初 item_children 对于所有行都是空的,但每个项目都有一个 item_parent_id 并且不为空。我想编写一个查询来查看所有行和相应的父 ID,并用逗号分隔的子 ID 字符串更新每一行的 item_children。

例如

item_full_name | item_id | item_owners | item_parent_id | item_children
item1          | 1       | o1, o2      | 2              | 
item2          | 3       | owner8      | 2              |
item3          | 2       | owner6      | 0              |
item4          | 4       | owner7      | 1              |

这应该转换为

item_full_name | item_id | item_owners | item_parent_id | item_children
item1          | 1       | o1, o2      | 2              | 4
item2          | 3       | owner8      | 2              |
item3          | 2       | owner6      | 0              | 3,1
item4          | 4       | owner7      | 1              |

任何指示都会有所帮助。谢谢!

我开始沿着递归 CTE 的道路前进,但后来意识到您只需要每个 parent 的 children 在那个单一级别。一种方法是通过 item_parent_id 聚合 item_id。然后,将您的原始 table 加入此结果以获得每个 parent.

的 children 的 CSV 列表
WITH cte AS (
    SELECT item_parent_id, STRING_AGG(item_id::text, ',') AS item_children
    FROM yourTable
    GROUP BY item_parent_id
)

SELECT
    t1.item_full_name,
    t1.item_id,
    t1.item_owners,
    t1.item_parent_id,
    t2.item_children
FROM yourTable t1
LEFT JOIN cte t2
    ON t1.item_id = t2.item_parent_id
ORDER BY
    t1.item_full_name;

Demo