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

后端 未结 13 1461
有刺的猬
有刺的猬 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:50

    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  
    

提交回复
热议问题