標籤: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分頁方式