I have self referenced table - HIERARCHY(id, name, parent_id)
.
So I need to get all the hierarchy by any node of this hierarchy. For example we have tree, where h1
, h2
are roots:
-(h1)
| |_(h1_1)
| | |_(h1_1_2)
| |_(h1_2)
| |_(h1_2_1)
-(h2)
| |_(h2_1)
| |_(h2_2)
|
What I need, it to get all the tree e.g with root h1
by any node of this tree e.g. by h1_2
-(h1)
|_(h1_1)
get | |_(h1_1_2) by h1_2 or h1_2_1, etc
|_(h1_2)
|_(h1_2_1)
I wrote the query:
WITH RECURSIVE hierarchy_with_parents(id) AS (
SELECT l.id, l.name, l.parent_id FROM hierarchy AS l WHERE l.id = <any_row_id>
UNION ALL
SELECT lc.id, lc.name, lc.parent_id FROM hierarchy lc, hierarchy_with_parents lwp WHERE lc.id = lwp.parent_id
), hierarchy_with_children(id) AS (
SELECT l.id, l.name, l.parent_id FROM hierarchy AS l WHERE l.id
IN ( -- sub-query for getting parent id
SELECT
lwp.id
FROM hierarchy_with_parents AS lwp
WHERE lwp.parent_id IS NULL
)
UNION ALL
SELECT lc.id, lc.name, lc.parent_id FROM hierarchy lc, hierarchy_with_children lwc WHERE lc.parent_id = lwc.id
)
SELECT * FROM hierarchy_with_children
hierarchy_with_parents
- returns subtree from child to parent(inclusive),
hierarchy_with_children
- returns all tree.
It seems all works Ok, but I am not DB-expert and I want to know limitations and comments about my query. Also any other solutions for PostgreSQL and Oracle 11g welcome.
Thanks.