子查询在 SELECT、UPDATE、DELETE 语句内部可以出现SELECT语句。内部的SELECT语句结果可以作为外部语句中条件子句的一部分,也可以作为外部查询的临时表。子查询的类型有:
查询中包查询 (SELECT 有两个以上)
分类
1.出现的位置
select 列的位置可以出现子查询语句
from 数据源也可以是子查询的结果集
where 结果作为条件存在
2.条件
看返回结果集的特点:
a. 单行单列(*****) 值类型结果集 可以使用 > < >= <= <> != where/having 中
b. 多行单列 集合类型结果集 可以使用 > >= < <= any all in not in
c. 单行多列 对象类型结果集 = in where中
d. 多行多列(*****) 数据源 用在from后面
单行单列
1.查询出公司工资最高的员工的详细信息
select*from emp where sal =(selectmax(sal)from emp);2.查询出工资大于平均工资的所有人
select*from emp where sal >(selectavg(sal)from emp);
多行单列
1.查询出大于30部门所有员工工资的员工信息
select*from emp e
where e.sal >all(select sal from emp where deptno =30);>all 表示比查询出来的结果集中最大的值还要大
<all 表示比查询出来的结果集中最小的值还要小
select*from emp
where sal >(selectmax(sal)from emp where deptno =30)2.查询出大于任意一个销售员工资的详细信息
select*from emp
where sal >any(select sal from emp where job ='销售员');>any 表示比查询出来的结果集中最小的值还要大
<any 表示比查询出来的结果集中最大的值还要小
3.查询出工资等于销售员工资的员工信息
select*from emp
where sal notin(select sal from emp where job ='销售员');
单行多列
--- 单行多列1.查询出和马云同一个部门,同一个职位的员工信息
select*from emp where(job,deptno)in(select job,deptno from emp where ename ='马云')2.查询出所有员工工资大于 30000的编号,姓名,部门名称
select e.empno,e.ename,(select d.dname from dept d where e.deptno = d.deptno) 部门编号
from emp e
where e.sal >30000;
注意: select放在字段列表中查询出来的结果只能是一列