子查询:也是实现多表查询的,在子查询中可以包含in any all 等关键字,也可以包含比较运算符等。子查询灵活多变。子查询经常出现的如下两个位置:
(1)where子句中的子查询
查询结果为单行单列的子查询
--》查询员工表中的工资比smith还要高的全部员工信息
select * from t_employee where sal>(select sal from t_wmployee where ename='smith');
查询结果为单行多列的子查询
-->查询员工表中工资和职位与smith一样的全部员工信息。
select * from t_employee where (sal,job)=(select sal,job from t_employee where ename='smith');
查询结果为多行单列的子查询
使用带关键字in的子查询
--》查询员工表中的数据,这些数据的部门号必须在部门表t_dept表中。
select * from t_employee where deptno in(select deptno from t_dept);
使用带关键字any的子查询
=any 功能和关键字in一样
>any >= 比子查询返回的数据中最小的还要大的数据
<any <= 比子查询返回的数据中最大的还要小
--》查询员工表姓名和工资,这些员工的工资不低于职位manager的工资
先查询员工表中职位为manager的工资
select sal from t_employee where job='manager';
select ename,sal from t_employee where sal>any(select sal from t_employee where job ='manager');
使用带有关键字all的子查询
>all >=all 比子查询返回的结果最大的还要大于的数据
<all <=all 比子查询返回的结果最小的还要小于的数据
--》查询员工的姓名和工资,这些员工的工资高于职位为manager的工资
select ename,sal from t_employee where sal>all(select sal from t_employee where job='manager');
from 子句中的子查询
特点:当子查询的返回结果是多行多列的时候,该子查询语句一般会在主查询语句from子句后边,子查询的结果被当做一张临时表的方式来处理
查询结果为多行多列的子查询
--》查询员工表中各部门的部门号,部门名称,部门地址,员工的人数,员工的平均工资。
select d.deptno,d.name,d.loc,count(e.ename),avg(e.sal) from t_employee e inner join t_dept d on e.deptno=d.deptno group by e.deptno;
子查询的方式完成
select d.deptno,d.dname,d.loc,num,average from t_dept d inner join (select deptno dno,count(ename) num,avg(sal) average from t_employee group by deptno) e on d.deptno=e.dno;