子查询
子查询就是嵌套在其他SQL语句内的查询语句,且必须出现在圆括号内(查询一般指select语句).
子查询的结果可以作为外层查询的过滤条件或计算字段(聚合函数)。
使用子查询过滤
子查询过滤一般与[not] in 结合使用,也可以使用其他运算符: > < = !=
select 字段1[,字段2...]
from 表1
where 字段1 [not] in (select 字段1 from 表2 where 条件)
#查找所在部门包含e的员工信息
select * from emp
where deptno in (select deptno from dept where deptno like '%e%');
同时 all,any,some是用于条件比较的关键字,用于比较一个值与子查询查询结果集中的多个值。
all:表示子查询结果集中的所有值进行比较,需要满足条件的是所有值
#佣金比所有人都高的员工
select * from emp
where sal > all(select ifnull(comm,0) from emp);
any:表示子查询结果集中随便一个值进行比较,只要有一个满足即可
#佣金比有的人工资还要高的员工
select * from emp
where ifnull(comm,0) > any(select sal from emp);
子查询作为计算字段
同时子查询也可以作为计算字段,括号中常与聚合函数配合使用
select
字段1,
字段2,
...,
(select 聚合函数 from 表2 [where 表2.字段1 = 表1.字段1])
from 表1 [where 条件];
#查询部门名和部门人数
select dname,(select count(*) from emp where emp.deptno = dept.deptno) as emps
from dept;