Skip to main content

概念:SQL语句中嵌套SELECT语句,称为嵌套查询,又称子查询。 select * from t1 where column1 = (select column1 from t2);

子查询外部的语句可以是insert/update/delete/select

标量子查询

子查询结果为单个值

值可为数字、字符串、日期等
常用的操作符:= <> > >= < <=
# 标量子查询
select id from dept where name = '销售部';
select * from emp where dept_id = (select id from dept where name = '销售部');
-- 查询在此时间段之后入职的员工
select * from emp where entrydate > (select entrydate from emp where name = '金庸');

表子查询

子查询结果为多行多列

常用 in

列子查询

子查询结果为一列

操作符描述
in在指定的集合范围之内,多选一
not in不在指定的集合范围之内
any子查询返回列表中,有任意一个满足即可
some与any等同,使用some的地方都可以使用any
all子查询返回列表的所有值都必须满足
# 列子查询
select * from emp where dept_id in (select id from dept where name = '销售部' or name = '市场部');
select salary from emp where dept_id = (select id from dept where name = '财务部');

行子查询

子查询结果为一行

常用的操作符:= <> in、not in
# 行子查询
select * from emp where (salary, managerid) = (select salary, managerid from emp where name = '张无忌');