就近原则,如果子查询内有符合 ‘emp’ 的 表/集合,就采用子查询内的,所以第二条语句的emp.deptno用的是子查询内的而不是子查询外的。
select a.empno ,a.ename ,a.sal ,a.deptno ,b.avgsal from emp a inner join ( select deptno ,avg(sal) as avgsal from emp b group by deptno ) b on b.deptno =a.deptno where a.sal > b.avgsal
未执行过。自行尝试。
员工薪水大于自己本部门的平均薪水 这一个问题?
select empno,ename,sal,(select avg(sal) from emp where deptno=e.deptno) avgsal from emp e where sal > (select avg(sal) from emp where deptno=e.deptno);
如果是该问题,avg(sal)是查询所有部门的平均薪水,嵌套select是为了得出本部门的薪水,
而且在该查询中,不能使用avg(sal),原因是:ORA-00937: 不是单组分组函数
没错,就是lz理解的那个意思。对于每一行记录而言,就是把主查询中表e的deptno赋值给了子查询中where条件约束,这样获得肯定是指定部门的平均薪水。