(1)连接查询
数据库中的各个表中存放着不同的数据,用户往往需要用多个表中的数据来组合、提炼出所需要的信息。如果一个查询需要对多个表进行操作,就称为连接查询 。
例
对student(sno,clno,sname,ssex,sage),course(cno,cname),sc(sno,cno,score)三张表进行操作
- 查询体育课成绩不及格的男生名单
select sname from sc,student ,course where sc.cno=course.cno and student.sno=sc.sno and ssex='男'and score<60 and cname='体育'
- 查询有多少名学生的物理课成绩不及格
select count(sno) from sc,course where sc.cno=course.cno and cname='物理' and score<60
当两个表中的列名相同时,引用列名要加上表名前缀,说明所指列属于哪个表,避免二义性。如果列名唯一则不需要加前缀。
(2)子查询
在 where 子句中包含另一个查询块,该查询块称为 子查询 或 嵌套查询 ,包含子查询的语句称为父查询或外部查询。
-
当子查询的返回值只有一个时,可以使用比较运算符( =、>、<、>=、<=、!=)将父查询和子查询连接起来。
-
如果子查询的返回值不止一个,而是一个集合时,则不能直接使用比较运算符,可以在比较运算符和子查询之间插入 ANY 或 ALL
-
常用以下操作符
-
ANY 含义为任何一个
-
IN 可以代替 “=ANY”
-
ALL 的含义是全部
-
<>ALL 的含义为不等于子查询结果中的任何一个值
-
NOT IN 可以替代“ <>ALL ”
-
EXISTS 的含义是存在的量词,其子查询不返回任何实际数据,它只返回逻辑值“真”或“假”
例
- 将 A 班全体学生的成绩置 0
update sc set score=0 where sno in(select sno from student where clno='A')
- 删除 B 班全体学生的选课记录
delete from sc where sno in(select sno from student where clno='B')
- 使用 exists关键字查询所有选修了 C1 号课程的学生的姓名
selec sname from student where exists (select * from sc where cno='C1'and sc.sno=student.sno)
- 查询其他班中比A班所有学生年龄都小的学生,并按年龄的降序输出
select * from student where sage < all(select sage from student where clno='04001')
and clno<>'04001'
order by sage desc