I'm trying to prepare a recursive query that will generate data about parent-child relationships within a single table.
Here's some test data:
CREATE TABLE test
(
id INTEGER,
parent INTEGER
);
INSERT INTO test (id, parent) VALUES
(2, 1),
(3, 1),
(7, 2),
(8, 3),
(9, 3),
(10, 8),
(11, 8);
1
/ \
2 3
/ / \
7 8 9
/ \
10 11
Excepted results:
-- id | ancestry | parent |
-- 1 | {1} | 1 |
-- 2 | {1,2} | 1 |
-- 3 | {1,3} | 1 |
-- 7 | {1,2,7} | 2 |
-- 8 | {1,3,8} | 3 |
-- 9 | {1,3,9} | 3 |
-- 10 | {1,3,8,10} | 8 |
-- 11 | {1,3,8,11} | 8 |
#Query 1 : Return all parents for children 11 - {1,3,8,11}. The problem here is that I don't know how to mark that the first parent of 11 is 8.
WITH RECURSIVE c AS (
SELECT 11 AS id
UNION
SELECT t.parent
FROM test AS t
JOIN c ON c.id = t.id
)
SELECT * FROM c;
Thanks in advance.