当前位置:操作系统 > Unix/Linux >>

关联子查询和嵌套子查询

关联子查询和嵌套子查询
 
Sql代码    www.zzzyk.com  
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)    
);    
 如上表,要查询所有低于本部门平均工资的员工信息
 
嵌套子查询:
Sql代码  
select * from emp a where a.sal < (select avg(sal) from emp b where b.deptno = a.deptno)  
 可以看出每条记录都要关联一个子查询(每条都要先查询自己的deptno,然后再子查询),这样效率不高
 
关联子查询:
Sql代码  
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 ;  
 
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,