Postgres query to get all the children ids

∥☆過路亽.° 提交于 2019-12-02 01:16:12

I started off going down the road of a recursive CTE, but then realized that you just want the children of each parent, at that single level. One approach is to aggregate the item_id by item_parent_id. Then, join your original table to this result to obtain the CSV list of children for each parent.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!