天天看點

limit語句的查詢耗時研究,sql性能問題limit語句的執行時間為什麼偏移量越大,查詢越費時?參考

limit語句的執行時間

我的MySQL中有一個表(table),裡面有450000條資料。下面這條SQL語句是将id排序後,查詢從第0位(偏移量)開始,往後的10條資料。

SELECT * FROM table order by id desc limit 0, 10
           
  • 1

注意這條語句是先執行order by,再按limit要求來查詢。

根據limit偏移量的不同,SQL語句執行時間的統計資料如下:

SQL Time Cost
limit 0, 8000 0.73s
limit 1000, 8000 0.92s
limit 10000, 8000 2s
limit 100000, 8000 3.3s

為什麼偏移量越大,查詢越費時?

  • 每條資料的實際存儲長度不一樣(是以必須要依次周遊,不能直接跳過前面的一部分)
  • 哪怕是每條資料存儲長度一樣,如果之前有過delete操作,那索引上的排列就有gap
  • 是以資料不是定長存儲,不能像數組那樣用index來通路,隻能依次周遊,就導緻偏移量越大查詢越費時

歸根結底,這個問題跟MySQL的資料存儲結構有關。

參考

  1. http://blog.csdn.net/fangwei1235/article/details/8621655
  2. http://stackoverflow.com/questions/1612957/mysql-index-configuration
  3. https://explainextended.com/2009/10/23/mysql-order-by-limit-performance-late-row-lookups/
  4. http://stackoverflow.com/questions/4481388/why-does-mysql-higher-limit-offset-slow-the-query-down
  5. order by是如何執行的,http://stackoverflow.com/questions/6954981/how-does-mysql-order-by-implemented-internally
  6. mysql 索引的原理,http://www.uml.org.cn/sjjm/201107145.asp
  7. MySQL存儲引擎MyISAM與InnoDB的優劣, https://www.pureweber.com/article/myisam-vs-innodb/
  8. 存儲引擎,http://coolshell.cn/articles/1846.html