Created
September 20, 2016 19:46
-
-
Save ekampp/cb871918adc0fc931cb02afa20c30651 to your computer and use it in GitHub Desktop.
Multi-table 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
uid | |
1 | |
2 |
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
id, source_id, target_id, value | |
1, 1, 2, a1 | |
2, 2, 3, a2 |
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
uid | |
1 | |
2 | |
3 |
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 questions_with_answers(uid) AS ( | |
SELECT | |
q.*, a.* | |
FROM | |
questions q | |
LEFT OUTER JOIN | |
answers a ON (q.id = a.source_id) | |
WHERE | |
q.id = 1 -- question start node ID | |
UNION ALL | |
SELECT | |
q.*, a.* | |
FROM | |
questions_with_answers qa | |
JOIN | |
questions q ON (qa.target_id = q.id) | |
LEFT OUTER JOIN | |
answers a ON (q.id = a.source_id) | |
) | |
SELECT uid FROM questions_with_answers WHERE source_id IS NOT NULL AND target_id IS NOT NULL |
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
id, value | |
1, q1 | |
2, q2 | |
3, q3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment