Assuming I have the tables student
, club
, and student_club
:
student {
id
name
}
club {
id
name
}
stude
WITH RECURSIVE two AS
( SELECT 1::integer AS level
, student_id
FROM tmp.student_club sc0
WHERE sc0.club_id = 30
UNION
SELECT 1+two.level AS level
, sc1.student_id
FROM tmp.student_club sc1
JOIN two ON (two.student_id = sc1.student_id)
WHERE sc1.club_id = 50
AND two.level=1
)
SELECT st.* FROM tmp.student st
JOIN two ON (two.student_id=st.id)
WHERE two.level> 1
;
This seems to perform reasonably well, since the CTE-scan avoids the need for two separate subqueries.
There is always a reason to misuse recursive queries!
(BTW: mysql does not seem to have recursive queries)