·概念
子查询
sub query,查询是在某个查询结果之上进行的(一条select语句内部包含了另外一条select语句),被嵌入的select语句称为子查询语句。
主查询
主要的查询对象,第一条select语句,确定了用户所有的数据目标(数据源),以及要具体得到的字段信息。
关系
- 子查询是嵌入主查询中的
- 子查询是辅助主查询的:要么作为条件,要么作为数据源
- 子查询可以独立存在:是一条完整的select语句
·分类
按位置分类:
- Where子查询:子查询出现where条件中
- From子查询:子查询出现在from数据源中(做数据源)
按结果(功能)分类:
- 标量子查询:子查询得到的结果是一行一列
- 列子查询:子查询得到的结果是一列多行
- 行子查询:子查询得到的结果是一行多列(多行多列)
(上面出现的位置都是在where之后) - 表子查询:子查询得到的结果是多行多列(出现的位置是在from之后)
- Exists子查询:返回的结果1 或者 0
·标量子查询
子查询得到的结果是一行一列
select * from 数据源 where 条件判断 = / <> (select 字段名 from 数据源 where 判断条件 )
--实例
--获取wkm的班级名字
--需求决定主查询,条件决定子查询
select * from my_class where id = (select id from my_student where stu_name = 'wkm');
·列子查询
子查询得到的结果是一列多行
select 主查询 where 条件 in (列子查询)
--实例
--获取已经有学生在班的所有班级名字
insert into my_class values (3,'3班'),(4,'4班');
select name from my_class where id in (select class_id from my_student);
·行子查询
子查询得到的结果是一行多列
行元素
字段元素是指一个字段对应的值,行元素对应的就是多个字段:多个字段合并作为一个元素参与运算,称之为行元素
主查询 where 条件 [(构造一个行元素)] = (行子查询)
--实例
--获取班级上年龄最大且身高最高的学生
select * from my_student where (stu_age,stu_height) = (select max(stu_age),max(stu_height) from my_student);
select * from my_student having stu_age = max(stu_age) and stu_height = max(stu_height);
--表面上是对的但是having 在order by 之后,而order by只返回第一行数据
·表子查询
子查询得到的结果是多行多列(出现的位置是在from之后,用于from数据源)
select 字段列表 from (表子查询) [as] 别名 [where] [group by] [having] [order by] [limit];
--获取每个班上身高最高的学生
select * from (select * from my_student order by stu_height desc) as temp group by class_id;
·exists 子查询
返回的结果1 或者 0
where exists --where 1 永远为真
--实例
--求出有学生在的所有班级
select * from my_class as c where exists (select stu_id from my_student as s where s.class_id =c.id)
·特殊关键字
·in
主查询 where 条件 in (列子查询)
·any
任意一个
= any(列子查询):条件在查询结果中有任意一个匹配即可,等价于in
<> any(列子查询):条件在查询结果中不等于任意一个
1 = any(1,2,3) ------ true
1 <> any(1,2,3) ------ true
·some
与any完全一样
·all
= all(列子查询):等于里面所有
<> all(列子查询):不等于里面所有