MySQL 查询同一字段中同时满足多个条件

 

分析:

1,先查询出01号同学学习的课程

SELECT C FROM sc WHERE S='01'

 2,查询学习该相关课程的同学编号

SELECT S FROM sc WHERE C in 
(SELECT C FROM sc WHERE S='01')

 可以看到,我们分别查询了3次,所以出现多个结果,因为是or关系,所以每个选择了1、2、3课程的同学都全部取出,

3,现在需要将出现次数为3的编号取出

SELECT S FROM sc WHERE C in 
(SELECT C FROM sc WHERE S='01') 
GROUP BY S HAVING COUNT(S) =3

 看到编号为1、2、3、4的同学选了与01号同学一致的课程

4,与student表进行连表查询,取出相关信息

SELECT a.* FROM
student a LEFT JOIN sc b
ON a.S = b.S WHERE b.S in (
SELECT S FROM sc WHERE C in 
(SELECT C FROM sc WHERE S='01') 
GROUP BY S HAVING COUNT(S) =3)
GROUP BY a.S 

posted @ 2020-01-08 09:04  jescs  阅读(12349)  评论(1编辑  收藏  举报