SQL语句带有exists谓词的子查询和相关子查询

(注:student是学生信息表,sc是学生选课表,course是课程信息表)

exists谓词查询

  1. 查询与其他所有学生年龄均不同的学生学号, 姓名和年龄
    (即不存在年龄相同的)
select sno,sname,sage from student s 
where not exists (select sage from student t where s.sage=t.sage and s.sno!=t.sno);
  1. 查询所有选修了1号课程的学生姓名
    (即存在选修了1号课程的学生)
select sname  from student 
where exists (select * from sc where student.sno=sc.sno and cno='1');
  1. 查询没有选修1号课程的学生姓名
    (即不存在选修了1号课程的学生)
select sname  from student 
where not exists (select * from sc where student.sno=sc.sno and cno='1');
  1. 查询选修了全部课程的学生姓名
    (即不存在没选的课程)
select sname from student 
where not exists (select * from course 
where not exists (select * from sc where student.sno=sc.sno and sc.cno=course.cno));
  1. 查询至少选修了 学生95002选修的全部课程的学生的学号
    (即不存在95002学生选修的课程没选)
select distinct sno from sc A 
where not exists (select * from sc B where B.sno='95002' and not exists 
(select * from sc C where A.sno=C.sno and C.cno=B.cno));
  1. 没有人选修的课程号cno和cname
select cno,cname from course C 
where not exists (select * from sc where sc.cno=C.cno );

相关子查询

  1. 查询每个学生的所选修的课程成绩最高的成绩信息(sno,cno,grade)
select * from sc  A  where grade=(select max(grade) from  sc where sno=A.sno );
  1. ☆查询所有学生都选修了的课程的课程号cno
    (通过比较当前课程号所选修的人数与SC表中的总共(去重后)人数)
SELECT distinct cno FROM sc 
WHERE CNO IN (SELECT CNO FROM SC GROUP BY CNO HAVING COUNT(SNO)
 =(SELECT COUNT(DISTINCT SNO) FROM SC));

小结:exists (sql语句 返回结果集为真) not exists (sql语句 不返回结果集为真)
exists : 强调的是是否返回结果集,不要求知道返回什么,返回结果集则条件成立,not exists相反。

  • 7
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值