How to filter SQL results in a has-many-through relation

后端 未结 13 1455
有刺的猬
有刺的猬 2020-11-21 05:17

Assuming I have the tables student, club, and student_club:

student {
    id
    name
}
club {
    id
    name
}
stude         


        
13条回答
  •  长发绾君心
    2020-11-21 05:51

    So there's more than one way to skin a cat.
    I'll to add two more to make it, well, more complete.

    1) GROUP first, JOIN later

    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);
    

    2) EXISTS

    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);
    

提交回复
热议问题