-
-
Save halcyon/ceb85d23e09c8410a80d to your computer and use it in GitHub Desktop.
This file contains hidden or 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
-- drop table bleh; | |
create table bleh (id char(2) Primary Key, | |
parent_id char(2) ); | |
insert into bleh VALUES ('A1', null); | |
insert into bleh VALUES ('A2', 'A1'); | |
insert into bleh VALUES ('A3', 'A2'); | |
insert into bleh VALUES ('A4', 'A3'); | |
insert into bleh VALUES ('B1', null); | |
insert into bleh VALUES ('B2', 'B1'); | |
insert into bleh VALUES ('B3', 'B1'); | |
insert into bleh VALUES ('B4', 'B2'); | |
WITH RECURSIVE p(id, parent_id) AS ( | |
SELECT id, parent_id | |
FROM bleh | |
WHERE bleh.id = 'B2' -- change to get a different tree/entry point | |
UNION ALL | |
SELECT b.id, b.parent_id | |
FROM p p | |
JOIN bleh b | |
ON b.id = p.parent_id), | |
c(id, parent_id) AS ( | |
SELECT id, parent_id | |
FROM p | |
WHERE p.parent_id IS NULL | |
UNION ALL | |
SELECT b.id, b.parent_id | |
FROM c c | |
JOIN bleh b | |
ON b.parent_id = c.id) | |
SELECT * FROM c | |
ORDER BY id; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment