分享三種高效率SQL語句分頁方法

來源:互聯網
上載者:User

1.如果有一個自動成長的id欄位,則:

定義二個變數:Page,PageCount

Select top PageCount * From [tb_code] Where id>=(select min(id) from (select top (Page-1)*PageCount+1 id from [tb_code] order by id desc) as t) order by id desc

原理,根據ID計算出(Page-1)頁的最小值,然後用TOP關鍵字及可解決問題。


2.SELECT TOP 10 id,username From [tb_code] where id not in
( SELECT TOP 20000 id FROM tb_code ORDER BY username)

優點:此方法可以根據表中的任一個欄位排序,在一個表中有幾百萬條記錄時,仍有很高的效率,缺點是在大資料量的情況下效率略遜於第一種


3.SELECT TOP 10 id,username From
(SELECT TOP page*pagecount id, username FROM tb_code ORDER BY username)
DERIVEDTBL ORDER BY username DESC

優點:此方法可以根據表中的任一個欄位排序.
缺點是效率最低


在SQL Server 2005中使用rownum分頁(rownum函數使用方法介紹)

比方說要從表USER中查看第10到第20條之間的資料,那麼SQL是這樣實現的

SELECT * FROM (SELECT rownum rowcount,USER.* FROM USER) WHERE ROWCOUNT >=10 AND ROWCOUNT <20

其中函數ROWNUM,用來記錄每一條資料所在的位置。

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.