Sql Server常見的幾種分頁方式

⒈offset fetch next方式【SqlServer2012及以上版本支持】【推薦】

1 select * from T_User
2 order by id
3 offset 5 rows            /*(頁數-1) * 條數 */    
4 fetch next 5 rows only    /* 條數 */

⒉row_number() over()方式【SqlServer2005以上版本支持】

1 select * from 
2 (select *,row_number() over(order by id) as orderId from T_User) as t
3 where t.orderId between 11 and 15
4 /* (頁數-1)* 條數 + 1 */
5 /* 頁數 * 條數 */

⒊top not in方式【適用於SqlServer2012以下版本】

1 select top 5 * from T_User
2 where id not in (select top 10 id from T_User)
3 
4 /* top 條數 */
5 /* top 條數 * 頁數 */

⒋max(主鍵)方式【本質上還是top方式,適用於SqlServer2012以下版本】

1 select top 5 * from T_User where id>=
2 (select max(id) from (select top 6 id from T_User order by  id asc) a) 
3 order by id;
4 /*top 條數*/
5 /*top(頁數-1)* 條數 + 1*/

分析:在數據量較大時

  top not in方式:查詢靠前的數據速度較快

  ROW_NUMBER() OVER()方式:查詢靠後的數據速度比上一種較快

  offset fetch next方式:速度穩定,優於前2種,但sql版本限制2012及以上纔可使用

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章