一:子查询的特点:
- 子查询可被嵌套在 select,insert,update,delete 等语句中
- 大多数情况下子查询充当中间结果集角色
- 子查询可进行嵌套,且根据内存及表达式复杂程度不同,嵌套限制也不同
- 任何可使用表达式的地方,都可以使用子查询,只要他返回的是单个值
二:子查询的分类:
- 按返回值的数量可分为:标量子查询,多值子查询
- 按子查询对外部依赖性:独立子查询,相关子查询
- 按比较运算符的不同性:IN,EXISTS,ANY,SOME,ALL等多种形式
三:子查询的使用:
- 首先创建两个表(学生表和教师表)
# 创建学生表 mysql> create table tb_student( -> stu_ID long, -> class varchar(5), -> score int -> ); Query OK, 0 rows affected (0.23 sec) # 创建教师表 mysql> create table tb_teacher( -> tea_ID long, -> class varchar(5), -> age int -> ); Query OK, 0 rows affected (0.49 sec)
- 将一些值插入到表中
insert into tb_student values(1, "A", 20); insert into tb_student values(2, "A", 30); insert into tb_student values(3, "A", 70); insert into tb_student values(4, "B", 60); insert into tb_student values(5, "B", 70); insert into tb_student values(6, "B", 80); insert into tb_teacher values(1, "A", 25); insert into tb_teacher values(2, "B", 40);
- 准备工作完毕,接下来进行子查询练习
- 例一:各班教师ID及其班级平均分数
mysql> select tea_ID, -> (select avg(score) from tb_student as s where s.class = t.class group by class) -> as Avg from tb_teacher as t; +--------+---------+ | tea_ID | Avg | +--------+---------+ | 1 | 40.0000 | | 2 | 70.0000 | +--------+---------+ 2 rows in set (0.00 sec)
- 例二:各班级教师年龄及其班级及格人数(60为及格线)
mysql> select age, -> (select count(*) from tb_student as s where s.class = t.class && s.score >= 60 group by class) -> as Count from tb_teacher as t order by Count desc; +------+-------+ | age | Count | +------+-------+ | 40 | 3 | | 25 | 1 | +------+-------+ 2 rows in set (0.00 sec)