1.分頁方案一:(利用Not In和SELECT TOP分頁)效率次之
語句形式:
SELECT TOP 10 * FROM TestTable
WHERE(ID NOT IN (SELECT TOP 20 id FROM TestTable ORDERBY id)) ORDERBYID
SELECT TOP 頁大小 * FROM TestTable
WHERE( ID NOT IN (SELECT TOP 每頁大小-1*待查詢頁數-1 id FROM 表 ORDERBY id)) ORDERBYID
思路:先查詢出待查詢頁以前的所有條數的id,查詢ID不在這些ID中的指定數量條數
2.分頁方案二:(利用ID大於多少和SELECT TOP分頁)效率最高
語句形式:
SELECT TOP 10 * FROM TestTable
WHERE(ID> (SELECT MAX(id) FROM(SELECT TOP20 id FROM TestTable ORDERBYid)AST))ORDERBYID
SELECT TOP 頁大小* FROM TestTable
WHERE(ID>(SELECTMAX(id)FROM(SELECT TOP 每頁大小*待查詢頁數-1 id FROM表 ORDERBYid)AST)) ORDERBYID
思路:先得到待查詢頁的以前所有條數id,得到它們當中最大的ID號,以此最大ID號爲標誌,查找比這個ID號大的指定條數
3.分頁方案三:
SELECT TOP PageSize * FROM(SELECT TOP nPage*PageSize * from YOURTABLE order by id)as a order by id desc
SELECT TOP 每頁條數 * FROM (SELECT TOP 待查詢頁*每頁條數) * from YOURTABLE order by id)as a order by id desc
思路:先正排序查詢出待查詢頁以前(包括當前頁)的所有條數,而後將其倒排序,取指定條數
4.分頁方案四:
(利用SQL的遊標存儲過程分頁)
create procedureSqlPager
@sqlstrnvarchar(4000),--查詢字符串
@currentpageint,--第N頁
@pagesizeint--每頁行數
as
setnocounton
[email=[ft=,2,]declare@P1int,--P1]declare@P1int,--P1[/email]是遊標的id
@rowcountint
[email=execsp_cursoropen@P1output,@sqlstr,@scrollopt=1,@ccopt=1,@rowcount=@rowcountoutput]execsp_cursoropen@P1output,@sqlstr,@scrollopt=1,@ccopt=1,@rowcount=@rowcountoutput[/email]
selectceiling([email=[ft=,2,]1.0*@rowcount/@pagesize)as]1.0*@rowcount/@pagesize)as[/email]總頁數--,@rowcountas總行數,@currentpageas當前頁
[email=set@currentpage=(@currentpage-1)*@pagesize+1]set@currentpage=(@currentpage-1)*@pagesize+1[/email]
[email=[ft=,2,]execsp_cursorfetch@P1,16,@currentpage,@pagesize]execsp_cursorfetch@P1,16,@currentpage,@pagesize[/email]
[email=[ft=,2,]execsp_cursorclose@P1]execsp_cursorclose@P1[/email]
setnocountoff
其它的方案:若是沒有主鍵,能夠用臨時表,也能夠用方案三作,可是效率會低。
建議優化的時候,加上主鍵和索引,查詢效率會提升。
1.Oracle:
select * from ( select row_.*, rownum rownum_ from ( query_SQL ) row_ where rownum =< max) where rownum_ >= min
2.SQL Server:
select top @pagesize * from tablename where id not in (select top @pagesize*(@page-1) id from tablename order by id) order by id
3.MySQL
select * from tablename limit position, counter
4.DB2
select * from (select *,rownumber() as ROW_NEXT from tablename) where ROW_NEXT between min and max
post