使用 Postgres RECURSIVE 创建后代视图
Use Postgres RECURSIVE to create a view of descendants
我正在尝试创建一个 postgres 视图,其中包含一种层次结构的哈希图。
我的层次结构 table 看起来像:
------------------
| id | parent_id |
------------------
| 1 | null |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
出于性能原因,我需要在我的程序代码中进行哈希表示
1 => [2,3,4]; 2 => [4]; ...
我可以通过这个查询得到 1 的所有 children:
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 编码的)列表,其中包含所有 children 个“10000”。
我的问题:
如何将其包装成查询输出为
的形式
---------------------------------
| hierarchy_id | children_ids[] |
---------------------------------
| 1 | [2,3,4] |
非常感谢!
编辑
我的问题有误。我需要所有后代,感谢@pozs 指出这一点。
而且我的例子有缺陷,我编辑了它。
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)
我正在尝试创建一个 postgres 视图,其中包含一种层次结构的哈希图。
我的层次结构 table 看起来像:
------------------
| id | parent_id |
------------------
| 1 | null |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
出于性能原因,我需要在我的程序代码中进行哈希表示
1 => [2,3,4]; 2 => [4]; ...
我可以通过这个查询得到 1 的所有 children:
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 编码的)列表,其中包含所有 children 个“10000”。
我的问题:
如何将其包装成查询输出为
的形式---------------------------------
| hierarchy_id | children_ids[] |
---------------------------------
| 1 | [2,3,4] |
非常感谢!
编辑
我的问题有误。我需要所有后代,感谢@pozs 指出这一点。
而且我的例子有缺陷,我编辑了它。
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)