Oracle數據庫分頁查詢的實現
一、分頁實現基本知識
1、oracle數據庫不存在mysql所具有的limit關鍵字,oracle分頁需要依賴其本身具有的僞列rownum來實現;
2、oracle數據庫的第一條數據從1開始,不同於mysql的第一條數據從零開始;
3、頁面大小:每頁顯示的數據行數
二、分頁查詢過程分析
1、頁面大小爲10;
頁碼(第幾頁) |
開始值 |
結束值 |
1 |
1 |
1*10 |
2 |
2 |
2*10 |
3 |
3 |
3*10 |
n |
n |
n*10 |
2、總頁數=數據總量/頁面大小
3、每頁結束值=頁碼*頁面大小
4、分頁sql:使用三層嵌套查詢實現;
4.1、第一層:實現僞列查詢,在結果集中加入僞列,並依據排序字段對錶中內容進行升序排序;
select rownum r, t.* from TableName t order by 排序字段 asc;
4.2、第二層:將第一層的查詢結果作爲臨時表,在第一層查詢結果集的基礎上依據僞列進行升序排序並查詢所有數據;
select * from (第一層) order by r asc;
4.3、第三層:將第二層的查詢結果作爲臨時表,在此基礎上依據僞列實現分頁;
select * from (第二層) where r >= 開始值 and r <= 結束值;
5、將以上三層嵌套形成最終分頁查詢SQL;
select * from(
select * from(
select rownum r, t.* from user_tab t order by id asc)
order by r asc)
where r >= 1 and r <= 1*10;