Skip to content

Instantly share code, notes, and snippets.

@arrowcircle
Last active December 12, 2015 01:28
Show Gist options
  • Save arrowcircle/4691354 to your computer and use it in GitHub Desktop.
Save arrowcircle/4691354 to your computer and use it in GitHub Desktop.
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