Created
July 6, 2015 07:57
-
-
Save fortytw2/e58d4c28ecbf02eef8bd to your computer and use it in GitHub Desktop.
recursive sql
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
WITH RECURSIVE cte (id, body, op_id, path, comment_id, depth) AS ( | |
SELECT id, | |
body, | |
op_id, | |
array[id] AS path, | |
comment_id, | |
1 AS depth | |
FROM comments | |
WHERE comment_id = 0 AND post_id = $1 | |
UNION ALL | |
SELECT comments.id, | |
comments.body, | |
comments.op_id, | |
cte.path || comments.id, | |
comments.comment_id, | |
cte.depth + 1 AS depth | |
FROM comments | |
JOIN cte ON comments.comment_id = cte.id | |
) | |
SELECT id, body, op_id, comment_id, path, depth FROM cte | |
ORDER BY path; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment