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

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

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

student {
    id
    name
}
club {
    id
    name
}
stude         


        
13条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-21 06:03

    If you just want student_id then:

        Select student_id
          from student_club
         where club_id in ( 30, 50 )
      group by student_id
        having count( student_id ) = 2
    

    If you also need name from student then:

    Select student_id, name
      from student s
     where exists( select *
                     from student_club sc
                    where s.student_id = sc.student_id
                      and club_id in ( 30, 50 )
                 group by sc.student_id
                   having count( sc.student_id ) = 2 )
    

    If you have more than two clubs in a club_selection table then:

    Select student_id, name
      from student s
     where exists( select *
                     from student_club sc
                    where s.student_id = sc.student_id
                      and exists( select * 
                                    from club_selection cs
                                   where sc.club_id = cs.club_id )
                 group by sc.student_id
                   having count( sc.student_id ) = ( select count( * )
                                                       from club_selection ) )
    

提交回复
热议问题