Mysql order by 和limit 同時使用的優化問題
阿新 • • 發佈:2021-07-30
關鍵欄位索引一定要加上!!!
1.Mysql 的order by 和 limit 一起使用時的BUG
select * from table_a where user_id = xx order by gmt_create desc limit xx
這樣的話,即使user_id加了索引,但還是會非常非常慢,關於這個問題的細節自行百度。
這個問題能不能解決?可以。而且不難
select * from ( select * from table_a where user_id = xx order by gmt_create desc ) a limit xx
2.資料量過大時limit分頁效率
當資料量大到一定量級後,比如有幾個text欄位的大表100萬條資料的時候
這個時候執行sql
select * from table_a limit 800000,10
只查了10條資料,但是非常非常慢!
因為根據limit的執行原理,這裡是查出前80W+10條資料,然後截掉前面的80W條資料。
這個問題能不能解決?也可以。
select * from trable_a where id in ( select id from trable_a limit 800000,10 ) a
3.利用 inner join 優化
SELECT a.* FROM batteryinfocopy a inner join (select id from batteryinfocopy where CreateTime between '2020-01-28 08:43:07' and '2020-01-29 08:43:07' ORDER BY CreateTime DESC LIMIT 99,10) b using(id);