Created
December 20, 2015 21:43
-
-
Save nwjsmith/8a75e6aaaffb9ccfe77e to your computer and use it in GitHub Desktop.
Recursive ancestors query for PostgreSQL
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
WITH RECURSIVE ancestors(id, name, created_at, updated_at) AS ( | |
SELECT categories.id, categories.name, categories.created_at, categories.updated_at | |
FROM categories, categorizations | |
WHERE categorizations.subcategory_id = '667C9DF5-48C0-496B-922A-1B7D743B1A39' | |
AND categories.id = categorizations.category_id | |
UNION ALL | |
SELECT categories.id, categories.name, categories.created_at, categories.updated_at | |
FROM categories, categorizations, ancestors | |
WHERE categorizations.subcategory_id = ancestors.id | |
AND categories.id = categorizations.category_id | |
) | |
SELECT * FROM ancestors |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment