子查询是另一个语句中的 SELECT 语句。
子查询也称为内查询(Inner Query),必须位于括号之中。包含子查询的查询称为外查询(Outer Query)。子查询支持多层嵌套,也就是子查询可以包含其他子查询。
小试牛刀
# 查询是男生的数据
select * from user where sex = 1;
select * from user where id in (select id from user where sex = 1);
虽然这样写是脱裤子放屁,但是意思就是这么个意思
先在子查询里面查出数据,再带入上层进行查询
需要考虑子查询的结果集是单个还是多个
- 子查询在where里面
- 子查询在form
- 子查询在select里面
create table users
(
id int(11) primary key auto_increment,
name varchar(8) not null,
age int(4),
sex bool default 0
);
# 查询超过男生平均年龄的男生
# 查询超过男生平均年龄的男生,并且把平均年龄显示出来
# 查询用户的年龄,平均年龄
# 查询用户的年龄,性别,对应性别的平均年龄
# 查询超过男生平均年龄的男生
select * from users where sex = 1 and age > (select avg(age) from users where sex = 1 group by sex);
# 查询超过男生平均年龄的男生,并且把平均年龄显示出来
select name, age, u1.ag from (select avg(age) as ag from users where sex = 1 group by sex) u1, users where users.age > u1.ag;
# 查询用户的年龄,平均年龄
select name, age, (select avg(age) from users) as ag from users;
# 查询用户的年龄,性别,对应性别的平均年龄
select name, age, sex, (select avg(age) from users u2 where u1.sex = u2.sex) as sex_ag from users u1;