Skip to content

Instantly share code, notes, and snippets.

@brendanmckenzie
Created August 1, 2020 02:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brendanmckenzie/914e0a916f160f76d2d8b4c18b910854 to your computer and use it in GitHub Desktop.
Save brendanmckenzie/914e0a916f160f76d2d8b4c18b910854 to your computer and use it in GitHub Desktop.
with recursive cte as (
select
child_id,
parent_id,
project_id,
array [child_id, parent_id] as path,
1 as level
from
child_parent
union all
select
p.child_id as child_id,
t.parent_id as parent_id,
t.project_id,
p.child_id || t.path as path,
t.level + 1 as level
from
child_parent p
inner join cte t on p.parent_id = t.child_id
where
not (p.child_id = any (t.path))
)
select
cte.level,
cte.path
from
cte
order by
cte.path;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment