1. 程式人生 > 實用技巧 >Mysql資料量較大時分頁查詢優化

Mysql資料量較大時分頁查詢優化

據表 collect ( id, title ,info ,vtype) 就這4個欄位,其中 title 用定長,info 用text, id是主鍵,vtype是int,vtype是索引。

最後collect 為 10萬條記錄,看下面這條sql語句:

select id,title from collect limit 1000,10; 很快;基本上0.01秒就OK。

再來看這條語句:

select id,title from collect limit 90000,10; 

從9萬條開始分頁,結果8-9秒完成,效能嚴重的差。

可以這樣優化:

select id from collect order by id limit 90000
,10; 很快,0.04秒就OK。

使用id主鍵做索引,速度沒得說。

改進後的方法:

select id,title from collect where id>=(select id from collect order by id 
limit 90000,1) limit 10;  

這條語句依然是用了id做索引的結果。

測試:

-- 建立索引查詢與沒有索引查詢比較
CREATE INDEX t_outstanding_treaty_assessdate ON t_outstanding_treaty(assessdate);

select * from t_outstanding_treaty where
assessdate = '2019-12-31';//當資料量較大時,時間差異較大 -- 提高分頁查詢效率
-- select *from table_name limit m,n;
如每頁10條資料,第三頁:3,10 m為 (3-1)*10=20 ==》20是要開始取數的位置的下標。 -- 每頁10條數 第300頁: (300-1)*10,10 2999 10

--原始 select * from t_outstanding_treaty LIMIT 2990,10select * from t_outstanding_treaty limit 2990,10; select * from t_outstanding_treaty order
by treatyid,sectionno,accperiod,uwyear,acccurrency,exchrate,exchratenew,freinscode,retreatyid,refreinscode,reacccurrency,reexchrate,reexchratenew,assessdate,acckind limit 2990,10;

可以參看連結:https://zhuanlan.zhihu.com/p/92552787深入研究。