Each of these queries work for a single id as well as for the whole table.
And you can return just the path / the full path or all other columns as well.
SELECT t.*, concat_ws('->', t1.path, t.name) AS full_path
FROM tbl t
LEFT JOIN LATERAL (
SELECT string_agg(t1.name, '->' ORDER BY i) AS path
FROM generate_subscripts(t.arrayofparents, 1) i
JOIN tbl t1 ON t1.id = t.arrayofparents[i]
) t1 ON true
WHERE t.id = 4; -- optional
Alternatively, you could move the ORDER BY
to a subquery - may be a bit faster:
SELECT concat_ws('->', t1.path, t.name) AS full_path
FROM tbl t, LATERAL (
SELECT string_agg(t1.name, '->') AS path
FROM (
SELECT t1.name
FROM generate_subscripts(t.arrayofparents, 1) i
JOIN tbl t1 ON t1.id = t.arrayofparents[i]
ORDER BY i
) t1
) t1
WHERE t.id = 4; -- optional
Since the aggregation happens in the LATERAL
subquery we don't need a GROUP BY
step in the outer query.
We also don't need LEFT JOIN LATERAL ... ON true
to retain all rows where arrayofparents
is NULL or empty, because the LATERAL
subquery always returns a row due to the aggregate function.
LATERAL
requires Postgres 9.3.
Use concat_ws()
to ignore possible NULL values in the concatenation.
SQL Fiddle.
WITH OTDINALITY
makes it a bit simpler and faster in Postgres 9.4:
SELECT t.*, concat_ws('->', t1.path, t.name) AS full_path
FROM tbl t, LATERAL (
SELECT string_agg(t1.name, '->' ORDER BY ord) AS path
FROM unnest(t.arrayofparents) WITH ORDINALITY a(id,ord)
JOIN tbl t1 USING (id)
) t1
WHERE t.id = 4;
Detailed explanation:
Variant with UNION ALL
for pg 9.3
SELECT t1.full_path
FROM tbl t, LATERAL (
SELECT string_agg(name, '->') AS full_path
FROM (
(
SELECT name
FROM generate_subscripts(t.arrayofparents, 1) i
JOIN tbl ON id = t.arrayofparents[i]
ORDER BY i
)
UNION ALL SELECT t.name
) t1
) t1
WHERE t.id = 4;