在PostgreSQL中递归创建JSON

时间:2019-03-06 10:37:41

标签: json postgresql recursion

假设我们有一个描述父母/孩子关系的简单表...

+-----------+----------+
| parent_id | child_id | 
+-----------+----------+
| 1         | 2        |
| 2         | 3        |
| 2         | 4        |
| 3         | 5        |
| 3         | 6        |
+-----------+----------+

我想描述如下所示的JSON对象中的那组关系:

{
    "id": 1,
    "children": [
        {
            "id": 2,
            "children": [
                {
                    "id": 3,
                    "children": [
                        {
                            "id": 5,
                            "children": []
                        },
                        {
                            "id": 6,
                            "children": []
                        }
                    ]
                },
                {
                    "id": 4,
                    "children": []
                }
            ]
        }
    ]
}

是否有可能获得该结构或接近的结构?我已经到了...

WITH RECURSIVE relations AS (
    SELECT
        relationship.child
     FROM relationship
    WHERE relationship.parent = 1
    UNION
    SELECT
        relationship.child
     FROM relationship
    INNER JOIN relations on relations.child = relationship.parent
)

SELECT parent, array_agg(child) as children
FROM relationship
WHERE parent IN (SELECT child from relations)
GROUP BY parent

哪个产生结果...

+--------+----------+
| parent | children |
+--------+----------+
| 2      | {3, 4}   |
| 3      | {5, 6}   |
+--------+----------+

所以感觉好像我可以接近,但是根本想不到如何从中得到最终结果。我尝试搜索stackoverflow,但找不到我想要的东西。任何帮助将不胜感激:)

0 个答案:

没有答案