Created
October 28, 2016 22:04
-
-
Save AlexWheeler/1bc8577a25d638b7faafca263e7242a4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
WITH RECURSIVE tree AS ( | |
SELECT id, ARRAY[]::INTEGER[] AS ancestors | |
FROM test WHERE parent_id IS NULL | |
UNION ALL | |
SELECT test.id, tree.ancestors || test.parent_id | |
FROM test, tree | |
WHERE test.parent_id = tree.id | |
) SELECT * FROM tree | |
--test table | |
id, parent_id | |
1, NULL | |
2, 1 | |
3, 1 | |
Result | |
id, ancestors | |
1 {} | |
2 {1} | |
3 {1} | |
but I want | |
id, ancestors | |
1 {2, 3} | |
2 {} | |
3 {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment