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

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

    SELECT s.stud_id, s.name
    FROM   student s,
    (
    select x.stud_id from 
    student_club x 
    JOIN   student_club y ON x.stud_id = y.stud_id
    WHERE  x.club_id = 30
    AND    y.club_id = 50
    ) tmp_tbl
    where tmp_tbl.stud_id = s.stud_id
    ;
    

    Use of fastest variant (Mr. Sean in Mr. Brandstetter chart). May be variant with only one join to only the student_club matrix has the right to live. So, the longest query will have only two columns to calculate, idea is to make the query thin.

提交回复
热议问题