Skip to content

Instantly share code, notes, and snippets.

@ekampp
Created September 20, 2016 19:46
Show Gist options
  • Save ekampp/cb871918adc0fc931cb02afa20c30651 to your computer and use it in GitHub Desktop.
Save ekampp/cb871918adc0fc931cb02afa20c30651 to your computer and use it in GitHub Desktop.
Multi-table recursive SQL
id, source_id, target_id, value
1, 1, 2, a1
2, 2, 3, a2
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
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