子查詢
---------------------------------[感謝天賜提供的圖片]
在sql語句中是可以做嵌套查詢的。及一個語句的結果可以作為另一個語句的條件,
理解子查詢的關鍵在於把子查詢當作一張表來看待。外層的語句可以把內嵌的子查詢返回的結果當成一張表使用。子查詢可以作為一個虛表被使用。
子查詢要用括弧括起來
將子查詢放在比較運算符的右邊(增強可讀性)
子查詢根據其返回結果可以分為單行子查詢和多行子查詢。
1.單行子查詢
當子查詢有單行時,可以取單行中的一個欄位形成單個值用於條件比較。
-- 查詢僱員其薪資在僱員平均薪資以上
-- [1] 查詢員工的平均薪資
select avg(e.sal) "AVGSAL"
from emp e
--[2] 查詢滿足條件的僱員
select *
from emp e
where e.sal > (select avg(e.sal) "AVGSAL" from emp e)
2.多行子查詢
-- 查在僱員中有哪些人是管理者
--【1】查詢管理者
select distinct e.mgr
from emp e
where e.mgr is not null
--【2】查詢指定列表的信息 in
select e.*
from emp e
where e.empno in (select distinct e.mgr
from emp e
where e.mgr is not null)
多行子查詢返回的結果可以作為「表」使用
3.From後的子查詢
子查詢可以作為一張續表用於from後。
-- 每個部門平均薪水的等級
--【1】部門的平均薪資
select e.deptno,avg(e.sal) "AVGSAL"
from emp e
group by e.deptno
--【2】求等級
select vt0.deptno,vt0.avgsal,sg.grade
from (select e.deptno,avg(e.sal) "AVGSAL"
from emp e
group by e.deptno) VT0,salgrade sg
where vt0.avgsal between sg.losal and sg.hisal
-- 99 join on
select vt0.deptno,vt0.avgsal,sg.grade
from (select e.deptno,avg(e.sal) "AVGSAL"
from emp e
group by e.deptno) VT0 join salgrade sg on vt0.avgsal between sg.losal and sg.hisal
4.TOP-N問題
把select得到的數據集提取前n條數。rownum:表示對查詢的數據集記錄的編號,從1開始。
-- 查詢前10名僱員
select e.*,rownum
from emp e
where rownum <= 10
rownum和order-by
-- 查詢按照薪資降序,前10名僱員
select e.*,rownum
from emp e
where rownum <= 10
order by e.sal desc
[1] order by 一定在整個結果集出現後才執行。
[2] rownum 在結果集出現後纔有編號。
。。。-> select -> rownum -> order by
-- 查詢按照薪資降序,前10名僱員
select vt0.*,rownum
from (select e.*
from emp e
order by e.sal desc) VT0
where rownum <= 10
5.分頁
-- 求查詢6-10號的僱員
select vt0.*
from (select e.*,rownum "RN"
from emp e
where rownum <= 10) VT0
where vt0.rn >= 6
將排序標號的表作為虛表子查詢返回值
求page=n,pagesize=size的數據
=>[(n-1)*size+1,n*size]
select vt0.*
from (select t.*, rownum 「RN」
from table t
where rownum <= n*size) VT0
where vt0.rn >= (n-1)*size+1
推薦閱讀: