Su consulta para el primer nivel (aquí depth
para distinguir de la tabla) debería verse así:
select l.name, h.child_id, 1 as depth
from level l
join level_hierarchy h on l.id = h.child_id
where h.parent_id is null;
name | child_id | depth
----------+----------+-------
Level1_a | 1 | 1
(1 row)
Tenga en cuenta que el uso adecuado de is null
(no use =
para comparar con null
como siempre da null
).
Puede usar lo anterior como una consulta inicial en una cte recursiva:
with recursive recursive_query as (
select l.name, h.child_id, 1 as depth
from level l
join level_hierarchy h on l.id = h.child_id
where h.parent_id is null
union all
select l.name, h.child_id, depth + 1
from level l
join level_hierarchy h on l.id = h.child_id
join recursive_query r on h.parent_id = r.child_id
)
select *
from recursive_query
-- where depth = 2
name | child_id | depth
----------+----------+-------
Level1_a | 1 | 1
Level2_b | 3 | 2
Level2_a | 19 | 2
Level3_a | 4 | 3
Level3_b | 5 | 3
Level4_a | 6 | 4
Level4_b | 7 | 4
(7 rows)