create table EMP
(
EMPNO NUMBER(4) not null,
ENAME VARCHAR2(10),
JOB VARCHAR2(9),
MGR NUMBER(4),
HIREDATE DATE,
SAL NUMBER(7,2),
DEPTNO NUMBER(2)
);
如上表,要查询所有低于本部门平均工资的员工信息
嵌套子查询:
select * from emp a where a.sal < (select avg(sal) from emp b where b.deptno = a.deptno)
可以看出每条记录都要关联一个子查询(每条都要先查询自己的deptno,然后再子查询),这样效率不高
关联子查询:
select a.* from emp a ,(select deptno,avg(sal) sal from emp group by deptno) b
where a.deptno=b.deptno
and a.sal < b.sal ;