子查询
概念:
SQL语句中嵌套SELECT语句,称为嵌套查询
,又称子查询
.SELECT * FROM t1 WHERE column1 = ( SELECT column1 FROM 12); | |||||||||
---|---|---|---|---|---|---|---|---|---|
子查询外部的语句可以是INSERT / UPDATE / DELETE / SELECT 的任何一个. |
---|
子查询类型
根据结果类型分类
列子查询
(可以是多行)
,这种子查询称为:列子查询.操作符 | 描述 |
---|---|
IN | 在指定的集合范围内,多选一 |
NOT IN | 不在指定集合范围内 |
ANY | 子查询返回列表中,有任意一个满足即可 |
SOME | 与ANY等同,使用SOME的地方都可以使用ANY |
ALL | 子查询返回列表的所有值都必须满足 |
Exercises1
-- 1.查询 "销售部" 和 "市场部" 的所有员工信息
-- a. 查询 '销售部' 和 '市场部' 的id
select id from dept where name = '销售部' or name = '市场部';
-- b. 根据部门 id ,查询员工信息
select * from emp where dept_id in (select id from dept where name = '销售部' or name = '市场部');
注意: 查询两个部门的 id , 用 or 连接, 而不是 and ; 因为 and 取的是 两个部门的交集 ,显然是空集. | |||||||||
---|---|---|---|---|---|---|---|---|---|
-- 查询比 财务部 所有人工资都高的员工信息
-- a 查询所有 财务部 人员工资
select id from dept where name = '财务部'; -- 先查询部门
select salary from emp where dept_id = (select id from dept where name = '财务部'); -- 查询财务部所有员工工资
-- b 查询比 财务部 所有人工资都高的员工信息
update emp set salary = 4800 where id = 8;
select * from emp where salary > all( select salary from emp where dept_id = (select id from dept where name = '财务部') );
Exercises3
-- 3. 查询比研发部其中任意一人工资高的员工信息
select salary from emp where dept_id = (select id from dept where name = '研发部');
select * from emp where salary > any(select salary from emp where dept_id = (select id from dept where name = '研发部'));