SQL分頁演算法

2021-06-14 19:10:59 字數 1415 閱讀 6804

sql分頁演算法的寫法參考了 金魚 的部落格

我在sqlserver2005資料庫表中插入128w條資料進行測試

表結構create table [dbo].[tbuser](

[id] [int] identity(1,1) not null,

[name] [varchar](50) null,

[***] [varchar](50) null,

[age] [int] null,

[birthday] [varchar](50) null,

[psd] [varchar](50) null

) on [primary]

方法一/

select top 200 *

from tbuser

where id not in

(select top (200*(90-1)) id

from tbuser

order by id

)order by id

///方法二

select top 200 *

from tbuser

where id>(

select isnull(max(id),0)

from  (

select top(200*(90-1)) id

from tbuser

order by id )a)

order by id

方法三select top 200 *

from

(select row_number() over(order by id) as rownumber,*

from tbuser 

)awhere rownumber>(200*(90-1))

order by id--此行是我加上去的,如果不加上去則id不連續

結果發現查詢效率跟金魚部落格描述的不一樣:

金魚部落格描述:

其它的方案:如果沒有主鍵,可以用臨時表,也可以用方案三做,但是效率會低。

建議優化的時候,加上主鍵和索引,查詢效率會提高。

通過sql 查詢分析器,顯示比較:我的結論是:

分頁方案二:(利用id大於多少和select top分頁)效率最高,需要拼接sql語句

分頁方案一:(利用not in和select top分頁)   效率次之,需要拼接sql語句

分頁方案三:(利用sql的游標儲存過程分頁)    效率最差,但是最為通用

而我測試的結果卻是:

方法一:2秒

方法二:10秒

方法三:1秒

把id設定成主鍵後結果:

方法一:0秒

方法二:0秒

方法三:0秒

疑問:方法二為什麼會慢那麼多,id沒設定主鍵導致的麼?

方法三據分析不是應該最慢嗎,但測試結果卻最快,是何原因?

SQL分頁演算法

create procedure pagination sqlstr nvarchar 4000 查詢字串 currentpage int,第n頁 pagesize int 每頁行數 asset nocount on declare p1 int,p1是游標的id rowcount int exec...

SQL儲存過程分頁演算法研究

1.俄羅斯儲存過程 的改良版 create procedure pagination1 pagesize int,頁面大小,如每頁儲存20條記錄 pageindex int 當前頁碼 as set nocount on begin declare indextable table id int id...

手寫分頁sql 分頁查詢SQL語句

表結構 drop table if exists zhoufoxcn userlist create table zhoufoxcn userlist userid int 10 unsigned not null auto increment,username varchar 45 not nul...