例:思考如何查詢比本部門平均薪水高的員工姓名,薪水。
--嵌套子查詢的寫法:
--我的理解寫法:
--第一步:先查詢員工姓名莲组,薪水
select ename,sal from emp;
--第二步:--每個(gè)部門的平均薪水,將其作為一個(gè)表
select avg(sal) avgSal,deptno from emp group by deptno;
--第三步:在前兩步基礎(chǔ)之上解題
select ename,sal,emp.deptno from emp,
(select avg(sal) avgSal,deptno from emp group by deptno) tab_avgSal
where sal > avgSal and emp.deptno = tab_avgSal.deptno;
--標(biāo)準(zhǔn)答案寫法 :
select empno,ename,sal
from emp e ,(select deptno,avg(sal) avgsal from emp group by deptno) d
where e.deptno =d.deptno
and e.sal >d.avgsal;
--相關(guān)子查詢解題
select empno,ename,sal,deptno
from emp outer
where sal > (select avg(sal) from emp where deptno = outer.deptno);
--父查詢中的行每被處理一次,子查詢就執(zhí)行一次
練習(xí)1
如下練習(xí)暖夭,使用相關(guān)子查詢完成
- 查詢比所在職位平均工資高的員工姓名锹杈,職位。
select ename,job
from emp outer
where sal > (select avg(sal) from emp where job = outer.job);
- 查詢工資為其部門最低工資的員工編號(hào)迈着,姓名竭望,工資。
select empno,ename,sal
from emp outer
where sal = (select min(sal) from emp where deptno = outer.deptno);
練習(xí)2
如下練習(xí)裕菠,用相關(guān)子查詢完成
- 查詢所有雇員編號(hào)咬清,名字和部門名字。
select empno,ename,
(select dname from dept where emp.deptno = deptno) dname
from emp;
- 查詢哪些員工是經(jīng)理奴潘?
select * from emp e
where 0 < (select count(*) from emp
where mgr = e.empno);
- 查詢哪些員工不是經(jīng)理旧烧?
select * from emp e
where 0 = (select count(*) from emp
where mgr = e.empno);
- 查詢每個(gè)部門工資最低的兩個(gè)員工編號(hào),姓名画髓,工資掘剪。
select empno,ename,sal,deptno
from emp outer
where 1 >= (select count(*)
from emp
where outer.sal > sal
and deptno = outer.deptno);
練習(xí)3
如下練習(xí),用exists或not exists完成
- 列出至少有一個(gè)雇員的所有部門名稱奈虾。
select dname
from dept d
where exists (select '1'
from emp,dept
where emp.deptno = dept.deptno
and d.dname = dname);
- 列出一個(gè)雇員都沒有的所有部門名稱夺谁。
select dname
from dept d
where not exists (select '1'
from emp,dept
where emp.deptno = dept.deptno
and d.dname = dname);
課后作業(yè)
如下練習(xí),使用相關(guān)子查詢完成肉微。
- 查詢薪水多于他所在部門平均薪水的雇員名字匾鸥,部門號(hào)。
select ename,deptno
from emp outer
where sal > (select avg(sal)
from emp
where outer.deptno = deptno);
- 查詢員工姓名和直接上級(jí)的名字碉纳。
select ename,(select ename
from emp
where outer.mgr = empno)
直接上級(jí)
from emp outer;
- 查詢每個(gè)部門工資最高的員工姓名勿负,工資。
select ename,sal,deptno
from emp outer
where sal = (select max(sal)
from emp
where outer.deptno = deptno);
- 查詢每個(gè)部門工資前兩名高的員工姓名村象,工資笆环。
select ename,sal,deptno
from emp outer
where 1 >= (select count(*)
from emp
where outer.deptno = deptno
and outer.sal > sal);
分割線
博主為咯學(xué)編程:父母不同意學(xué)編程,現(xiàn)已斷絕關(guān)系;戀人不同意學(xué)編程厚者,現(xiàn)已分手;親戚不同意學(xué)編程躁劣,現(xiàn)已斷絕來(lái)往;老板不同意學(xué)編程,現(xiàn)已失業(yè)三十年。库菲。账忘。。。鳖擒。如果此博文有幫到你歡迎打賞溉浙,金額不限。蒋荚。戳稽。