使用Postgres RECURSIVE创建后代视图

时间:2017-05-17 14:12:32

标签: sql performance postgresql recursive-query

我正在尝试创建一个postgres视图,其中包含一种层次结构的哈希映射。

我的层次结构表看起来像:

------------------
| id | parent_id |
------------------
|  1 |      null |
|  2 |         1 |
|  3 |         1 |
|  4 |         2 |

出于性能原因,我需要在程序代码中进行哈希重新定位

1 => [2,3,4]; 2 => [4]; ...

我可以通过此查询获得1的所有孩子:

WITH RECURSIVE
    h_tree(id, label)
  AS (
    SELECT
      id,
      label
    FROM hierarchy
    WHERE parent_id = 10000
    UNION ALL
    (
      SELECT
        h.id,
        h.label
      FROM h_tree v, hierarchy h
      WHERE h.parent_id = v.id
    )
  )
SELECT array_to_json(ARRAY_AGG(id)) AS children_ids
FROM h_tree

此查询为我提供了一个(json编码的)列表,其中包含" 10000"的所有子项。

我的问题:

如何在此查询输出为

的表单中包装它
---------------------------------
| hierarchy_id | children_ids[] |
---------------------------------
|            1 |        [2,3,4] |

非常感谢!

修改

我的问题出错了。我需要所有的后代,谢谢@pozsfor指出这一点。

此外我的例子有缺陷,我编辑了它。

1 个答案:

答案 0 :(得分:2)

WITH RECURSIVE children AS
   (SELECT parent_id AS id, id AS child_id
    FROM hierarchy
    WHERE parent_id IS NOT NULL
    UNION
    SELECT children.id, h.id
    FROM children
      JOIN hierarchy h
         ON h.parent_id = children.child_id
   )
SELECT hierarchy.id,
       string_agg(children.child_id::text, ',')
FROM hierarchy
   LEFT JOIN children USING (id)
GROUP BY hierarchy.id;

┌────┬────────────┐
│ id │ string_agg │
├────┼────────────┤
│  1 │ 2,3,4      │
│  2 │ 4          │
│  3 │            │
│  4 │            │
└────┴────────────┘
(4 rows)
相关问题