Last active
December 12, 2015 01:28
-
-
Save arrowcircle/4691354 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
def subtree_ids_sql(depth) | |
tree_sql = <<-SQL | |
WITH RECURSIVE search_tree(id, path, depth) AS ( | |
SELECT id, ARRAY[id], 1 | |
FROM users | |
WHERE id = #{id} | |
UNION ALL | |
SELECT users.id, path || users.id, search_tree.depth + 1 | |
FROM search_tree | |
JOIN users ON users.parent_id = search_tree.id | |
WHERE NOT users.id = ANY(path) AND search_tree.depth <= #{depth} | |
) | |
SELECT id FROM search_tree where search_tree.id != #{id} ORDER BY path | |
SQL | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment