天天看點

3種SQL語句分頁寫法

在開發中經常會使用到資料分頁查詢,一般的分頁可以直接用SQL語句分頁,當然也可以把分頁寫在存儲過程裡,下面是三種比較常用的SQL語句分頁方法,下面以每頁5條資料,查詢第3頁為例子:

      第一種:使用not in,select top 方法:

select top 5 * from T_user where ID not in(select top (3-1)*5 id from T_user order by ID)

說明:select top 頁大小 [要查詢的字段名稱] from 表名 where ID not in(select top (目前頁數-1)*頁大小 id from 表名 order by ID)      

  第二種:使用select top ,max方法:

select top 5 * from T_user where(ID>=(select MAX(id)from(select top (3-1)*5+1 ID from T_user order by ID)as t))order by ID
說明:select top 頁大小 [要查詢的字段名稱] from 表名 where(ID>=(select Max(id)from(select top(目前頁數-1)*頁大小+1) ID from 表名 order by ID)as t)order by ID)      

   第三種:如果SQLServer是2005及以上版本,可以使用ROW_NUMBER()函數進行分頁:

select * from
(
select *, row_number()over(order by id) as num from T_user 
)as t where t.num between (3-1)*5+1 and 3*5
說明:select * from(select [要查詢的字段名稱], row_number()over(order by id) as num from 表名 )as t where t.num between (目前頁-1)*頁大小+1 and 目前頁*頁大小      

  以上三種方法,從效率上講方法一相對來說比較慢,二和三相差不大。。