学习目标:
一、嵌套查询的基本概念
二、嵌套查询的分类(谓词分类)
1、带有IN谓词的子查询
2、带有比较运算符的子查询
3、带有ANY或ALL谓词的子查询
4、带有EXISTS谓词的子查询
学习内容:
一、嵌套查询的基本概念
查询块:一个select语句成为一个查询块
嵌套查询:将一个查询块嵌套在另一个查询块的where子句或having短语的条件中的查询
子查询的限制:
二、嵌套查询的分类(谓词分类)
1、带有IN谓词的子查询
父查询和子查询之间用IN进行连接,子查询结果是一个集合
--查询与“刘晨”在同一个系的学生
--1.确定“刘晨”所在系名
--2.查找所有在IS系的学生
select sno,sname,sdept from student
where sdept In
(select sdept from student
where sname='刘晨');
用自身连接实现上题:
select s1.sno,s1.sname,s1.sdept from student s1,student s2
where s1.sdept=s2.sdept and s2.sname='刘晨';
--查询选修了课程名为“信息系统”的学生学号和姓名
select sno,sname from student
where sno In
(select sno from sc
where cno In
(select cno from course
where cname='信息系统')
);
2、带有比较运算符的子查询
适用范围:当能确切知道内层查询返回单值时,可用比较运算符与ANY 或 ALL谓词配合使用
--找出每个学生超过他选修课程平均成绩的课程号
select sno,cno from sc x
where grade >
(select avg(grade) from sc y
where y.sno=x.sno);
--或者 内层可以不取别名
select sno,cno from sc x
where grade >
(select avg(grade) from sc
where sno=x.sno);
子查询一定要跟在比较符之后
3、带有ANY或ALL谓词的子查询
ANY 任意一个值
ALL 所有值
--查询其他系中比IS系所有学生年龄都大的学生学号和姓名
select sname,sage from student
where sage > ALL
(select sage from student
where sdept='IS');
4、带有EXISTS谓词的子查询
带有EXISTS谓词的子查询不返回任何实际数据,他只产生逻辑真值‘true’,或者逻辑假值‘false’
--查询所有没选修1号课程的学生姓名
select * from student s;
select * from sc;
select sname from student s
where not exists
(select * from sc
where s.sno=sno and cno=1);
--查询选修了全部课程的学生姓名
select sname from student s
where not exists
(select * from course c
where not exists
(select * from sc
where s.sno=sno and c.cno=cno));