场景:查找身高最高的学生
按照身高降序排序,取得第一个select * from select_student order by height desc limit 0,1;
问题是出现等高的学生,问题不能处理!
应该,找到最高的身高,然后找到所有符合最高身高的学生select max(height) from select_student;select * from select_student where height=180.05;
上面两条语句可以整合为一条语句:select * from select_student where height=select max(height) from select_student;
此时,select max() 出现在另外的语句内部,称之为子查询语句!
注意:子查询,应该始终出现括号内!select * from select_student where height=(select max(height) from select_student);
子查询的分类:
分类的依据:
1,依据子查询出现的位置
where型子查询,出现在where子句内
from型子查询,出现在from子句内
2,依据子查询的返回数据的格式
标量子查询,返回值是一个数据,称之为标量子查询
列子查询,返回一个列
行子查询,返回一个行
表子查询,返回的是一个二维表
from型:
场景:查询下表每个班级之内,身高最高的学生
应该先将每个班最高的放置在班内的第一个位置,再按照班级进行分组
不能使用order by 再使用group by
而需要,先用一个查询,得到身高排序结果,再将该结果分组
留意:from需要一个数据还是一个表,需要将子查询返回的数据,导出成表即可!为子查询起个别名即可!select * from (select * from select_student order by height desc) as tmp group by class_id;
列子查询
返回值应该是一列
由于返回的是一列,是一类数据,看成是一个数据的集合。
查询所有班内女同学的男学生信息:
条件:先确定哪些班级内有女生:
select class_id from select_student where gender='female' group by class_id;
再在该班级之内,找到所有的男生:
select * from select_student where gender='male' and class_id in
(select class_id from select_student where gender='female' group by class_id);
典型的列子查询使用 in or not in 作为子查询的条件!
列子查询,还可以使用 =some , !=all 或者其他的运算符配合 some() 和 all() 语法完成!
some() 表示集合中的一部分! =some()相当于in , !=some()不相当于 not in !
all() 表示集合中的全部!(!=all() 相当于not in)
行子查询
场景:找到最高,最富有的学生!select * from select_student where height=(select max(height) from select_student)
and money=(select max(money) from select_student);
上面的代码可以简化为:select * from select_student where (height,money) = (select max(height),max(money)
form select_student;
使用行子查询可以,一次性查出来一个行(多个行)使用行进行匹配!上面使用了(),构建了一行!与子查询的行作比较!
exists型子查询
判断依据不是根据子查询所返回的数据!只是根据子查询是否存在的返回数据来看;
语法:exists(子查询);
如果子查询存在返回数据,则exists返回真,反之返回假!
出现在where条件内:select * from select_student where exists(select 1);
场景:
检索出班级已经不存在的学生select * from select_student where exists(select * from select_class where
select_student.class_id=select_class.id);