1.子查询的介绍
在一个select语句中,嵌入另外一个select语句,那么被嵌入的select语句称之为子查询语句,外部那个select语句称为主查询。
主查询与子查询的关系:
- 子查询是嵌入到主查询中
- 子查询是辅助主查询的,要么充当条件,要么充当数据源
- 子查询是可以独立存在额语句,是一条完整的select语句
2.子查询的使用
例1:查询大于平均年龄的学生:
select * from students where age > (select avg(age) from students);
例2:查询学生在班(c_id不为空)的所有班级名字:
select name from classes where id in (select c_id from students where c_id is not null);
例3:查找年龄最大,身高最高的学生:
select * from students where age=(select max(age) from students) and height=(select max(height) from studetns);
--简写
select * from students where (age, height) = (select max(age),max(height) from students);
3.小结:
子查询是一个完整的查询语句,子查询被嵌入到一对小括号里面。
先执行子查询语句,然后主查询根据子查询的结果再查询。