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相反。

猜你喜欢

转载自blog.csdn.net/iTaylorfan/article/details/106203344