-
理解
一个查询语句中内嵌另一个完整的查询语句,被嵌套的语句 称为子查询 或者内查询
外面的语句称为主查询 或者外查询 -
语法
select (子查询)
from (子查询)
where (子查询) -
特点
- 子查询 必须写在小括号中
- 子查询 优先执行 ,主查询需要用到子查询的结果
- 子查询结果
单行子查询:结果只有一个 搭配的符号 = > < >= <= <>
多行子查询:结果多个 搭配的符号 in / not in all() any()
能单表的就不多表
能多表就不子查询
# 1. 单行子查询
# 案例1:查询薪资比'smith'的薪资高的员工信息
-- 先查出smith的薪资
select sal from EMP where ename = 'smith';
select * from EMP where sal > (select sal from EMP where ename = 'smith');
结果:
# 案例2:查询部门地址loc 是 NEW YORK或者CHICAGO的部门中所有的员工的信息
-- 先找部门地址loc 是 NEW YORK或者CHICAGO 部门编号
select deptno from DEPT where loc in('NEW YORK','CHICAGO');
select * from EMP
where deptno in(select deptno from DEPT where loc in('NEW YORK','CHICAGO'));
结果
#查询员工的最高薪资并显示员工的姓名
select sal,ename from EMP order by sal desc limit 1;
方式2
-- 最高薪资
select max(sal) from EMP;
select sal,ename from EMP where sal = (select max(sal) from EMP);
结果
# 案例3:查询其他部门中比部门10中的 任意一个员工薪资都低的员工薪资、名字
-- 求出部门10的最低薪资
select min(sal) from EMP where deptno = 10;
select ENAME from EMP where deptno != 10
and sal < (select min(sal) from EMP where deptno = 10);
结果
-- all() 所有
-- 查询小于部门10的薪资
select sal from EMP where deptno = 10;
select sal from EMP where deptno != 10
and sal < all(select sal from EMP where deptno = 10);
# 案例4:查询其他部门中比部门10中的 任一一个员工薪资都低的员工薪资、名字
-- 求出部门10的最高薪资
select max(sal) from EMP where deptno = 10;
select * from EMP where deptno != 10
and sal < (select max(sal) from EMP where deptno = 10);
结果:
-- any()
-- 查询出部门10的薪资
select sal from EMP where deptno = 10;
select * from EMP where deptno != 10
and sal < any(select sal from EMP where deptno = 10);
结果: