Assuming I have the tables student
, club
, and student_club
:
student {
id
name
}
club {
id
name
}
stude
SELECT *
FROM student
WHERE id IN (SELECT student_id
FROM student_club
WHERE club_id = 30
INTERSECT
SELECT student_id
FROM student_club
WHERE club_id = 50)
Or a more general solution easier to extend to n
clubs and that avoids INTERSECT
(not available in MySQL) and IN
(as performance of this sucks in MySQL)
SELECT s.id,
s.name
FROM student s
join student_club sc
ON s.id = sc.student_id
WHERE sc.club_id IN ( 30, 50 )
GROUP BY s.id,
s.name
HAVING COUNT(DISTINCT sc.club_id) = 2