Mysql子查询的概念、分类、语法


wKiom1Zb4xayly9_AABlk1iuVTY168.jpg


场景:查找身高最高的学生php

按照身高降序排序,取得第一个ide

select * from select_student order by height desc limit 0,1;

wKiom1Zb3v6y5JGDAAC1E75UqSs856.jpg

问题是出现等高的学生,问题不能处理!spa

应该,找到最高的身高,而后找到全部符合最高身高的学生3d

select max(height) from select_student;
select * from select_student where height=180.05;


上面两条语句能够整合为一条语句:orm

select * from select_student where height=select max(height) from select_student;


此时,select max() 出如今另外的语句内部,称之为子查询语句blog

注意:子查询,应该始终出现括号内!排序

select * from select_student where height=(select max(height) from select_student);


子查询的分类:get

    分类的依据:it

    1,依据子查询出现的位置
io

        where型子查询,出如今where子句内

        from型子查询,出如今from子句内

    2,依据子查询的返回数据的格式

        标量子查询,返回值是一个数据,称之为标量子查询

        列子查询,返回一个列

        行子查询,返回一个行

        表子查询,返回的是一个二维表



  • from型:


场景:查询下表每一个班级以内,身高最高的学生


wKioL1Zb5QPSGvupAABUMQ7zDoo853.jpg


应该先将每一个班最高的放置在班内的第一个位置,再按照班级进行分组

不能使用order by 再使用group by

而须要,先用一个查询,获得身高排序结果,再将该结果分组


留意:from须要一个数据仍是一个表,须要将子查询返回的数据,导出成表便可!为子查询起个别名便可!

select * from (select * from select_student order by height desc) as tmp group by class_id;

wKioL1Zb5oXx4iA6AABU2pN0k48116.jpg


  • 列子查询    

返回值应该是一列

wKioL1Zb553R_Gr8AAAdxXmB9FI533.jpg


因为返回的是一列,是一类数据,当作是一个数据的集合。


查询全部班内女同窗的男学生信息:

条件:先肯定哪些班级内有女生:

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);
相关文章
相关标签/搜索