子查询:
概念:SQL语句中嵌套SELECT语句,称为嵌套查询,又称子查询
- 标量子查询(子查询结果为单个值)
- 列子查询(子查询结果为一列)
- 行子查询(子查询结果为一行)
- 表子查询(子查询结果为多列多行)
select * from t1 where column1 = (select column1 from t2);
一、标量子查询
概念:子查询返回的结果是单个值(数字、字符串、日期);常用操作符:= <> > >= <=
案例A:查询销售部的所有员工信息
#常规方法
#1,查询“销售部”的部门ID
select id from dept where name = "销售部";
#2,根据部门ID查询员工信息
selece * from emp where dept_id = "4"; #此处假设查询出来的ID是4
#标量子查询方法:
sele * from emp where dept_id = (select id from dept where name = "销售部");
案例B:查询在“韦一笑”入职日期后的员工信息
select * from emp
where entrydate > (select entrydate from emp where name = "韦一笑");
二、列子查询
概念:子查询返回的结果是一列(可以多行);常见的操作符:in not in any some all
案例A:查询销售部和市场部的所有员工信息
select * from emp where dept_id in
(select dept_id from dept where name = "销售部" or name = "市场部");
案例B:查询比财务部所有人工资都高的员工信息
select * from emp where money > (select money from dept where name = "财务部")
三、行子查询
概念:子查询返回的结果是一行(可以多列);常见的操作符: = <> in not in
案例A:查询与"灭绝"的薪资及其直属领导相同的员工信息
select * from emp where (money,boss) = (select money,boss from emp where name = "张无忌");
四、表子查询
概念:子查询返回的结果是多行多列;常见的操作符:in
案例A:查询与“小昭”、“灭绝”职位和薪资相同的员工信息
select * from emp where (money,job) in
(select money,job from emp where name = "小昭" or name = "灭绝"); #该子查询返回多行多列,故用in
案例B:查询入职日期是2006-01-01之后的员工信息和其部门信息
select e.*,d.* from (select * from emp where entrydate > "2016-01-01")
as e left join dept as d on e.dept_id = d.id;