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 SERIAL UNIQUE,
parent integer references test(id),
text text NOT NULL
);
with:
INSERT INTO test(parent, text) VALUES
(NULL, 'first'),
(1, 'second'),
(2, 'third'),
(3, 'fourth'),
(NULL, 'top'),
(5, 'middle'),
(6, 'bottom');
How do I get a tree with a particular item and all it's parents concatenated (or in an array) given it's id?
So far I have the following query to see what is being returned, but I can't seem to add the right WHERE clause to return the right value:
WITH RECURSIVE mytest(SRC, ID, Parent, Item, Tree, JOINED) AS (
SELECT '1', id, parent, text, array[id], text FROM test
UNION ALL
SELECT '2', test.id, test.parent, test.text as Item, NULL,
concat(t.joined, '/', test.text)
FROM mytest as t
JOIN test ON t.id = test.parent
)
SELECT * FROM mytest;
This gives me the entire set but as soon as I add something like WHERE id = 1 I don't get the results I expect (I'm looking for a concatenated list of the item and parents).
See Question&Answers more detail:
os