Assuming I have the tables student
, club
, and student_club
:
student {
id
name
}
club {
id
name
}
stude
So there's more than one way to skin a cat.
I'll to add two more to make it, well, more complete.
Assuming a sane data model where (student_id, club_id)
is unique in student_club
.
Martin Smith's second version is like somewhat similar, but he joins first, groups later. This should be faster:
SELECT s.id, s.name
FROM student s
JOIN (
SELECT student_id
FROM student_club
WHERE club_id IN (30, 50)
GROUP BY 1
HAVING COUNT(*) > 1
) sc USING (student_id);
And of course, there is the classic EXISTS
. Similar to Derek's variant with IN
. Simple and fast. (In MySQL, this should be quite a bit faster than the variant with IN
):
SELECT s.id, s.name
FROM student s
WHERE EXISTS (SELECT 1 FROM student_club
WHERE student_id = s.student_id AND club_id = 30)
AND EXISTS (SELECT 1 FROM student_club
WHERE student_id = s.student_id AND club_id = 50);