I am trying to create a postgres view, containing a kind of hash map of an hierarchical structure.
My hierarchy table looks something like:
------------------
| id | parent_id |
------------------
| 1 | null |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
For performance reasons i need, in my program code, a hashed represantation
1 => [2,3,4]; 2 => [4]; ...
I can get all children of 1 by this query:
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
This query gives me a (json encoded) list of all children of "10000".
My question:
How do I wrap this in a form where the output of this query is
---------------------------------
| hierarchy_id | children_ids[] |
---------------------------------
| 1 | [2,3,4] |
Thanks a lot!
EDIT
I made an error in my question. I need all descendants, thanks @pozsfor pointing that out.
Furthermore my example was flawed, I edited it.
Select label as hierarchy_ID, string_agg(id,',') From h_tree group by labelinstead of array_to_jason to combine multiple rows into one for each hierarchy_ID/label? I'm a bit confused becuase I don't see where hierarchy_ID is coming from unless it's label.RECURSIVEquery for all descendants. For just children, all you need is a simpleJOIN(or rather, a simpleSELECTif you don't need anything other than the children'sid). F.ex. rextester.com/VGTKE62744