Oracle資料庫實現分頁

2021-08-09 04:42:19 字數 1876 閱讀 5254

oracle中通過rownum實現分頁,rownum是乙個偽列,在普通的查詢中是不可見的,需要取出資料後rownum才會有值。

例如我們需要查詢員工表中的員工資訊,並且顯示出資料的序號。*

select rownum as 序號, ename as 姓名, sal as 工資

這裡的rownum可以根據意思看成行號。

知道了rownum是什麼,我們就很容易使用這個偽列來對查詢的結果集進行分頁。

查詢工資從高到低的員工資訊,以一頁5條資料分頁,查詢出第二頁

-- 第一步,查詢出所有資訊,並根據工資排序

select sal, ename, from emp where sal is

notnull

order

by sal

-- 第二步,取得排序後的序號,過濾掉10行以後的資料

select rownum as rn, sal, ename

from(

select sal, ename, from emp where sal is

notnull

order

by sal

) x

where rownum <= 10

--第三步,在前10行資料中再過濾掉6行以前的資料

select rn as 序號, ename as 姓名, sal as 工資

from(

select rownum as rn, sal, ename

from(

select sal, ename, from emp where sal is

notnull

order

by sal

) where rownum <= 10

)where rn >= 6

--另外一種寫法

select rn as 序號, ename as 姓名, sal as 工資

from(

select rownum as rn, sal, ename

from(

select sal, ename, from emp where sal is

notnull

order

by sal

)) awhere a.rn between 6

and10

在這裡為什麼不直接在第一步就取出rownum呢?因為如果第一步就取出rownum

select rownum as rn, sal, ename, from emp where sal is

notnull

order

by sal

這條查詢語句執行的順序是:先取出資料(包括rownum),再排序。所以取出來的資料可能是這樣的:

rn     sal    ename

------- ------- ---------

13000 tom

42888 jones

152560 ford

211300 adams

3900 simth

...

在第二步中取出rownum能保證rownum為排序後的rownum(1,2,3,4,…),而不是排序之前的rownum。

與mysql相比相對比較麻煩,mysql中只要使用關鍵字limit就能指定資料的開始下標和條數。

--從第六條開始,取五條資料

select * from emp limit(6,5);

ORACLE資料庫分頁

create proc p show querystr nvarchar 4000 表名 檢視名 查詢語句 pagesize int 10,每頁的大小 行數 pagecurrent int 1,要顯示的頁 fdshow nvarchar 4000 要顯示的字段列表,如果查詢結果有標識字段,需要指定此...

Oracle 資料庫分頁

1.oracle 資料庫分頁 要實現資料庫的分頁,需要知道記錄的總條數totalcount,以及頁碼page,每頁的大小pagesize。1 action protected int totalcount 總條數 protected int pagesize 每頁大小 protected int p...

Oracle資料庫分頁

在oracle資料庫中進行分頁查詢需要借助rownum偽列,並且查詢語句一共分為三層 第三層限制最小記錄數 第二層限制最大記錄數 第一層做條件限制 例如 將employees表中的employee id,first name分頁顯示,每頁十條記錄。那麼第一頁 select from select f...