按照身高降序,再取得第一个学生
select * from select_student order by height desc;
select * from select_student order by height desc limit 0,1;
问题是出现等高的学生,问题不能处理
应该,找到最高的身高,然后再找到所有符合身高的学生
select * from select_student where height=(select max(height) from select_student);
此时,max() 出现在另外的语句内部,称之为子查询!
子查询的概念与分类
出现在其他语句内部的查询语句,称之为子查询(sub_query)! 注意:子查询,应该始终出现在括号里
子查询的分类:
select
分类的依据!两种: 1:依据 子查询的位置
where型子查询,出现在where子句内 from型子查询,出现在from子句内 2:依据子查询的返回数据的格式
标量子查询,返回值是一个数据,称之为标量子查询 列子查询,返回一个列 行子查询,返回一个行 表子查询,返回是一个二维表
子查询语法介绍
from型子查询
示例:查询,每个班级内,最高的学生
应该先将每个班最高的放置在班内的第一个位置,再按照班级进行分组! 不能使用order by 再 group by
而需要,先用一个查询,得到身高排序结果,再将该结果分组 select * from select_student order by class_id,height desc
select * from(select * from select_student order by class_id,height desc) group by class_id;
留意:from后面需要是一个表,需要将子查询返回的数据,导出成表才即可!为子查询起个别名即可解决:
select * from(select * from select_student order by class_id,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 , not in 作为列子查询的条件
列子查询还可以使用: =some , 表示集合中的一部分 !=all , 集合中的全部
或者其他的运算符配合 some() and all() 语法完成!
select * from select_student where gender='male' and class_id =some(select class_id from select_student where gender='female' group by class_id); 结果与上面的 in 语句完全一样!
面试题:
=some相当于in吗?
!=some 相当于 not in 吗? 答案:不相当于 not in
哪个相当于 not in ,与集合内的任何一个值都不相等,因此 !=all 相当于 not in
any就是 some ,一个功能
行子查询
场景:找到最高最有钱的学生
select * from select_student where height=(select max(height) from select_student) and
money=(select max(money) from select_student);
可以简化写成: select_student);
select * from select_student where (height,money) = (select max(money),max(height) from
使用行子查询可以一次性查出一个行(多个行)使用行进行匹配! 上面使用了括号()运算符,构建了一行!与子查询的行作比较!
exists型子查询
判断依据不是根据子查询所返回的数据,只是根据子查询是否存在返回数据来看 语法:exists(子查询);
如果子查询存在返回数据,则exists返回真,反之返回假 出现在where条件内: 示例1:
select * from select_student where exists (select 1);
示例2:查找出班级不存在的学生 首先删除一个班级数据:
select * from select_student where not exists(select * from select_class where select_student.class_id = select_class.id);
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- igbc.cn 版权所有 湘ICP备2023023988号-5
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务