Oracle系列:(14)子查询
子查询的作用:查询条件未知的事物 查询条件已知的问题:例如:查询工资为800的员工信息 查询条件未知的问题:例如:查询工资为20号部门平均工资的员工信息 一个条件未知的问题,可以分解为多个条件已知的问题 查询工资比WARD高的员工信息 第一:查询WARD的工资? selectsalfromempwhereename='WARD'; 第二:查询工资比1250高的员工信息? select*fromempwheresal>1250; 子查询: select* fromemp wheresal>( selectsal fromemp whereename='WARD' ); 查询'SALES'部门的员工信息(方式一:子查询) 第一:查询部门名为'SALES'的编号? selectdeptnofromdeptwheredname='SALES'; 第二:查询部门号为30的员工信息? select*fromempwheredeptno=30; 子查询: select* fromemp wheredeptno=( selectdeptno fromdept wheredname='SALES' ); 子查询细节: 1)子查询与父查询可以针对同一张表 2)子查询与父查询可以针对不同张表 3) 子查询与父查询在传统参数时,数量要相同 4) 子查询与父查询在传统参数时,类型要相同 5) 子查询与父查询在传统参数时,含义要相同 查询部门名为'SALES'的员工信息(方式二:多表查询) selectemp.* fromdept,emp where(dept.deptno=emp.deptno)and(dept.dname='SALES'); 查询每个员工编号,姓名,部门名,工资等级(三表查询,这三张表并无外健关联) selecte.empno,e.ename,d.dname,s.grade fromempe,deptd,salgrades where(e.deptno=d.deptno)and(e.salbetweens.losalands.hisal); 查询工资最低的员工信息(单行子查询,使用=号) 第一:查询出工资最低是多少? selectmin(sal)fromemp; 第二:查询工资为800的员工信息? select*fromempwheresal=800; 子查询: select* fromemp wheresal=( selectmin(sal) fromemp ); 查询部门名为'ACCOUNTING'或'SALES'的员工信息(多行子查询,使用in关键字) 第一:查询部门名为'ACCOUNTING'或'SALES'的部门编号? selectdeptnofromdeptwherednamein('ACCOUNTING','SALES'); 第二:查询部门号为10或30号的员工信息? select*fromempwheredeptnoin(10,30); 子查询: select* fromemp wheredeptnoin( selectdeptno fromdept wherednamein('ACCOUNTING','SALES') ); 查询工资比20号部门【任意any】一个员工工资【低<】的员工信息(多行子查询,使用any关键字) 第一:查询20号部门的所有工资? selectsalfromempwheredeptno=20; 第二:查询工资比(800,2975,3000,1100,3000)任意一个低的员工信息? select*fromempwheresal<any(800,3000); 在oracle看来,<any就等于<集合中最大的那个值 子查询: select* fromemp wheresal<any( selectsal fromemp wheredeptno=20 ); 查询工资比30号部门【所有all】员工【低<】的员工信息(多行子查询,使用all关键字) 第一:查询出30部门所有员工的工资? selectsalfromempwheredeptno=30; 第二:查询工资比(1600,1250,2850,1500,950)中所有的工资都低的员工信息? select*fromempwheresal<all(1600,950); 子查询: select* fromemp wheresal<all( selectsal fromemp wheredeptno=30 ); |