Created
March 16, 2015 09:12
-
-
Save knmkr/b104e543e01ce67dc03b to your computer and use it in GitHub Desktop.
PostgreSQL WITH RECURSIVE example
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 IF EXISTS my_tree; | |
CREATE TABLE my_tree (id integer, parent integer); | |
INSERT INTO my_tree VALUES (1, null), (2, 1), (3, 1), (4, 3); | |
-- | |
-- 1 | |
-- / \ | |
-- 2 3 | |
-- | | |
-- 4 | |
WITH RECURSIVE r AS ( | |
SELECT * FROM my_tree WHERE id = 1 | |
UNION ALL | |
SELECT my_tree.* FROM my_tree, r WHERE my_tree.parent = r.id | |
) | |
SELECT * FROM r ORDER BY id; | |
-- http://lets.postgresql.jp/documents/technical/with_recursive |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment