I have a table in PostgreSQL that contains:
id name arrayofparents
1 First
2 Second {1}
3 Second_Sec {1,2}
4 Third {1,2,3}
5
you can combine muliple operations like generate_subscripts and array to get the result:
with mtab as (
SELECT id, name, array_append(arrayofparents,id) as arrayofparents,
generate_subscripts(array_append(arrayofparents, id), 1) AS p_id FROM tab where id=2
)
select distinct array_to_string(
array(
select tab.name from tab join mtab t on tab.id=t.arrayofparents[t.p_id]
), '->'
) ;
live example Sqlfiddle
or use outer join combined with any:
SELECT coalesce(string_agg(p.name, '->') || '->' || t.name, t.name) AS parentnames
FROM tab AS t
LEFT JOIN tab AS p ON p.id = ANY(t.arrayofparents)
where t.id =7
GROUP BY t.id, t.name
live example Sqlfiddle