常用SQL Server分頁方式

來源:互聯網
上載者:User

標籤:des   style   blog   color   ar   資料   art   div   sp   

 

假設有表ARTICLE,欄位ID、YEAR...(其他省略),資料53210條(客戶真實資料,量不大),分頁查詢每頁30條,查詢第1500頁(即第45001-45030條資料),欄位ID叢集索引,YEAR無索引,Sqlserver版本:2008R2

第一種方案、最簡單、普通的方法:

SELECT TOP 30 *  FROM [ARTICLE] WHERE ID NOT IN ( SELECT TOP 45000 ID                     FROM [ARTICLE]                    ORDER BY YEAR DESC                             ,ID DESC ) ORDER BY YEAR DESC          ,ID DESC 

第二種方案:

SELECT *  FROM( SELECT TOP 30 *          FROM ( SELECT TOP 45030 *                   FROM ARTICLE                  ORDER BY YEAR DESC                           ,ID DESC ) f         ORDER BY f.YEAR ASC                  ,f.ID DESC ) s ORDER BY s.YEAR DESC          ,s.ID DESC 

第三種方案:

SELECT *  FROM ARTICLE w1       ,( SELECT TOP 30 ID            FROM ( SELECT TOP 50030 ID                                    ,YEAR                     FROM ARTICLE                    ORDER BY YEAR DESC                             ,ID DESC ) w           ORDER BY w.YEAR ASC                    ,w.ID ASC ) w2 WHERE w1.ID = w2.ID ORDER BY w1.YEAR DESC          ,w1.ID DESC 

第四種方案:

SELECT *  FROM ARTICLE w1 WHERE ID IN       ( SELECT TOP 30 ID           FROM ( SELECT TOP 45030 ID                                   ,YEAR                    FROM ARTICLE                   ORDER BY YEAR DESC                            ,ID DESC ) w          ORDER BY w.YEAR ASC                   ,w.ID ASC ) ORDER BY w1.YEAR DESC          ,w1.ID DESC 

第五種方案:

SELECT w2.n       ,w1.*  FROM ( SELECT TOP 50030 Row_number() OVER (ORDER BY YEAR DESC, ID DESC) n                          ,ID           FROM ARTICLE ) w2       ,ARTICLE w1 WHERE w1.ID = w2.ID       AND w2.n > 50000 ORDER BY w2.n ASC 

在查詢頁數靠前時,效率3>4>5>2>1,頁碼靠後時5>4>3>1>2,再根據使用者習慣,一般使用者的檢索只看最前面幾頁,因此選擇3 4 5方案均可,若綜合考慮方案5是最好的選擇

常用SQL Server分頁方式

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.