子查询分为外部查询语句和子查询语句
外部查询一条语句 子查询遍历一边
select * from emp e where e.deptno = (select d.deptno from dept d where d.dname = 'SALES')
单行子查询
是指返回一行的子查询,可以使用的运算符有= > < >= =< <>
select e.empno,e.ename,e.sal from emp e where e.sal >(select min(sal) from emp) and e.sal<(select max(sal) from emp) ;
单行子查询 子查询返回的值必须是单行的 不然会报错
单行子查询返回多行值常见错误写法
select * from emp e where e.sal < (select sal from emp);
多行子查询
多行子查询是指返回多行的子查询语句 可以使用的连接符有 in all any
多行子查询常见写法
select * from emp e where e.empno in (select e1.empno from emp e1 where e1.job<>('SALESMAN') ) ;
子查询和外链接很像 两者有共通之处
子查询写法
select * from emp e where e.deptno in (select d.deptno from dept d where d.deptno<>10) ;
左外链接写法
select *
from emp e
left join dept d
on e.deptno = d.deptno
where d.deptno <> 10;
左外链接加号写法
select * from emp e ,dept d
where e.deptno = d.deptno(+)
and d.deptno <> 10
any用法
要使用any运算符必须和单行操作符结合使用
求:部门编号不为10的员工工资 ,切员工工资大于部门标号为10的员工工资
select * from emp e where e.sal> any(select e1.sal from emp e1 where e1.deptno = 10) where e.deptno<>10;
all用法和any类似
all也必须和单行操作符结合使用
求:大于所有部门标号为30的员工工资的员工的所有信息
select * from emp e where e.sal> all(select e1.sal from emp e1 where e1.deptno = 30) ;
关联子查询
子查询中要用到外层查询的值 外层查询也要用到子查询结果的查询类型叫做关联子查询
求:员工工资大于同职业的员工信息
select e.empno 员工编号,e.ename 员工姓名,e.job 工作,sal 工资 from emp e where e.sal >(select avg(sal) from emp e1 where e1.job = e.job) order by sal desc ;
关联查询必须遍历表中的每条数据 速度较慢