How can I concatenate a list of parent items in a RECURSIVE CTE with PostgreSQL (version 10.2)?
For example, I have:
CREATE TABLE test (
id SERIA
In the top-down method the initial query should select only roots (items without parents), so the query returns each row only once:
with recursive top_down as (
select id, parent, text
from test
where parent is null
union all
select t.id, t.parent, concat_ws('/', r.text, t.text)
from test t
join top_down r on t.parent = r.id
)
select id, text
from top_down
where id = 4 -- input
If your goal is to find a specific item, the bottom-up approach is more efficient:
with recursive bottom_up as (
select id, parent, text
from test
where id = 4 -- input
union all
select r.id, t.parent, concat_ws('/', t.text, r.text)
from test t
join bottom_up r on r.parent = t.id
)
select id, text
from bottom_up
where parent is null
Remove final where conditions in both queries to see the difference.
Test it in rextester.