查询选修语文(cno=21)的学生名单
SELECT sname FROM student WHERE EXISTS ( SELECT 1 FROM sc WHERE sc.cno = 21 AND sc.sno = student.sno )
查询没有选修语文(cno=21)的学生名单
SELECT sname FROM student WHERE NOT EXISTS ( SELECT 1 FROM sc WHERE sc.cno = 21 AND sc.sno = student.sno )
选修全部课程的学生名单 (子查询)
SELECT sname FROM student WHERE sno in ( SELECT sc.sno FROM sc GROUP BY sc.sno HAVING count(1) = (SELECT count(1) from course) )
选修全部课程的学生名单 (exists)
select * from student t where not exists ( select * from course s where not exists (select * from sc where t.sno=sc.sno and s.cno= sc.cno ) )
当有课程没有选修时,下面的查询有返回的记录数。当全部课程都选择时,返回空
( select * from course s where not exists
(select * from sc where t.sno=sc.sno and s.cno= sc.cno )
)
数据库表结构
--课程表 CREATE TABLE `course` ( `cno` int(11) NOT NULL DEFAULT '0', `cname` varchar(255) DEFAULT NULL, PRIMARY KEY (`cno`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4; INSERT INTO `course` VALUES ('20', '数学'); INSERT INTO `course` VALUES ('21', '语文'); INSERT INTO `course` VALUES ('22', '外语'); --课程学生表 CREATE TABLE `sc` ( `sno` int(11) NOT NULL DEFAULT '0', `cno` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`sno`,`cno`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4; INSERT INTO `sc` VALUES ('10', '20'); INSERT INTO `sc` VALUES ('10', '21'); INSERT INTO `sc` VALUES ('11', '20'); INSERT INTO `sc` VALUES ('11', '21'); INSERT INTO `sc` VALUES ('11', '22'); INSERT INTO `sc` VALUES ('12', '22'); --学生表 CREATE TABLE `student` ( `sno` int(11) NOT NULL DEFAULT '0', `sname` varchar(255) DEFAULT NULL, PRIMARY KEY (`sno`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4; INSERT INTO `student` VALUES ('10', 'zhangsan'); INSERT INTO `student` VALUES ('11', 'lisi'); INSERT INTO `student` VALUES ('12', 'wangwu');