子查询


子查询: sub query 查询是在某一个查询结果之上进行的 (一条select语句内部包含了另外一条select语句).

子查询分类:

1. 按位置分类 : 子查询(select语句)在外部查询(select语句)中出现的位置

from子查询 : 子查询跟在from之后

where子查询 : 子查询出现在where条件中

exists子查询 : 子查询出现在exists 里面

2. 按照结果分类: 按照子查询得到的数据进行分类(理论上任何一个查询得到的结果都是二维表)

标量子查询 : 子查询得到的结果是一行一列

列子查询 : 子查询得到的结果是一列多行 使用 in 关键字

行子查询 : 子查询得到的结果是多列一行(多列多行)上面的子查询出现的位置都是在where之后

表子查询 : 子查询得到的结果是多行多列(出现的位置是在from之后)

在使用子查询的时候使用到的关键字:

any , some , all ;

=any 等价于 in , some等价于any , all 为全部

行子查询

行子查询 : 返回的结果可以是多行多列(一行多列)

需求: 查询整个学生中的年龄最大且身高最高的学生

步骤:

1.确实数据源

select * from student where age = ? and hight = ?

2.确实最大年龄和最大身高

select max(age) ,max(higent) from student;

注意

max函数不能使用在where之后,因为where查询的时候数据还没有进入到内存中 ,要想使用max函数 可以使用having子句,但是使用行子查询可以使用max函数,因为子查询的时候子查询语句已经将数据查询到了内存之中了

构造行元素:基本语法

select * from student where

-- (age,height)称之为行元素

(age,height) = (select max(age) ,max(height) from student);

另外一种实现方式 :(有缺点,数据具有不确定性不能限制数据的条数)

select * from student order by age desc ,height desc limit 1;

表子查询

表子查询:子查询返回的结果是多行多列的二维表

需求: 找出每个班最高的一个学生.

步骤

1.确定数据源 : 现将学生按照身高按照降序排序

select * from student order by height desc;

2.从每个班选出一个学生

select * from student group by Id ;

表子查询 : from子查询,得到的结果作为------from的数据源;

基本语法:

-- from ( select 子查询 ) as 表名 where条件/group by 条件;

-- 将子查询作为数据源 需要as 别名

select * from (select * from student order by height desc) as student group by id;

exists子查询

exists :是否存在,exists子查询就是用来判断某些条件是否满足(跨表),exists是拼接 在where之后,exists 返回的结果只有0和1;

需求: 查询所有的学生,前提是班级存在

步骤:

1.确定数据源

select * from student where ?;

2. 确实条件是否满足

exists(select * from class where Id = ?);

-- 是否成立