sql 分页
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?
總結
- 上一篇: TCP中的Flag options
- 下一篇: 我的故事在这里