一、選擇分頁演算法
下面是顛倒TOP分頁演算法
pagesize: 每頁顯示記錄數
cureentpage:當前頁數
select * from ( select TOP pagesize * FROM ( SELECT TOP pagesize*cureentpage * from news ORDER BY addtime DESC ) as a ORDER BY addtime ASC ) as b ORDER BY addtime DESC
這樣就可以把每頁的資料返回,加上索引可以提高查詢效率
select count(*) from news
返回總記錄數
二、程式設計
Page.java
- package com.test.util
- public class Page(){
- private int pagesize;//一頁的記錄數
- private int currentpage;//當前頁
- private int rowcount;//總記錄數
- private int pagecount;//計算的總頁數
-
- //變數初始化
- public Page(int currentpage, int rowcount){
- pagesize = 10;
- pagecount = rowcount/pagesize + 1;//計算總頁數
- this.currentpage = currentpage;
- this.rowcount = rowcount;
- }
-
- //返回總記錄
- public int getPageCount(){
- return pagecount;
- }
- //返回每頁的記錄數
- public int getPageSize(){
- return pagesize;
- }
-
- //返回判斷狀態,如果第一頁,返回0,最後一頁返回1,如果平常頁返回2
- public int checkCurrent(){
- if(current == 1){
- return 0;
- }
- if(current == pagecount){
- return 1;
- }
- else{
- return 2;
- }
- }
- }
action中的調用
int currentpage = Integer.parseInt(request.getParameter("page"));
String sql = "select count(*) from news";
ResultSet rs = stms.executeQuery(sql);
rs.next();
int rowcount = rs.getInt(1);
rs.close();
Page p = new Page(currentpage,rowcount);
int pagecount = p.getPageCount();
int flag = p.checkCurrent();
int pagesize = p.getPageSize();
ResultSet rs1 = null;
if(flag == 0){
sql = "select top "+pagesize +" * from news order by addtime DESC";
rs1 = stms.executeQuery(sql);
....................
}
if(flag == 1){
int pagelast = rowcount - ((pagecount - 1) * pagesize);
sql = "select * from (select top "+pagelast +" * from news order by addtime ASC) as a order by addtime DESC";
rs1 = stms.executeQuery(sql);
....................
}
else{
int pagelast = rowcount - ((pagecount - 1) * pagesize);
sql = "select * from ( select TOP pagesize * FROM ( SELECT TOP pagesize*cureentpage * from news ORDER BY addtime DESC ) as a ORDER BY addtime ASC ) as b ORDER BY addtime DESC";
rs1 = stms.executeQuery(sql);
....................
}
.....................
以上是我對使用顛倒TOP法實現的分頁功能,十分簡單
在效率上,支援200萬條資料應該沒有問題
PS:如果把SQL查詢運用到預存程序中,會不會更有效率呢?