sql >> Base de Datos >  >> RDS >> PostgreSQL

¿Cómo mostrar a los abuelos en la jerarquía sql?

Estás en el camino correcto. Considere usar esto:

with recursive tree as (
  select id, 
         parent_id, 
         array[id] as all_parents,
         name as parent_name
  from hierarchy
  where parent_id = 0
  union all 
  select c.id, 
         p.parent_id,
         p.all_parents,
         p.parent_name 
  from hierarchy c
     join tree p
      on c.parent_id = p.id 
     and c.id <> all (p.all_parents) 
)
select id, parent_id, parent_name
  from tree;

Demostración