MySQL最佳化order by導致的 using filesort

來源:互聯網
上載者:User

MySQL最佳化order by導致的 using filesort

using filesort 一般出現在 使用了 order by 語句當中。

using filesort不一定引起mysql的效能問題。但是如果查詢次數非常多,那麼每次在mysql中進行排序,還是會有影響的。

這裡的最佳化方式是在order by 的欄位建立索引,例如 語句:

SELECT * FROM yw_syjgb  ORDER BY result_date desc LIMIT 0,1000;

 查看執行計畫:

+----+-------------+----------+------+---------------+------+---------+------+---------+----------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+----------+------+---------------+------+---------+------+---------+----------------+
| 1 | SIMPLE | yw_syjgb | ALL | NULL | NULL | NULL | NULL | 1312418 | Using filesort |
+----+-------------+----------+------+---------------+------+---------+------+---------+----------------+


則需要在result_date  建立索引:

此時查看執行計畫:

+----+-------------+----------+-------+---------------+-------------+---------+------+------+-------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+----------+-------+---------------+-------------+---------+------+------+-------+
| 1 | SIMPLE | yw_syjgb | index | NULL | result_date | 6 | NULL | 1000 | NULL |
+----+-------------+----------+-------+---------------+-------------+---------+------+------+-------+

可以看到執行計畫中使用索引後沒有 Using filesort

需要注意的是:由於 Using filesort是使用演算法在 記憶體中進行排序,MySQL對於排序的記錄的大小也是有做限制:max_length_for_sort_data,預設為1024
show variables like '%max_length_for_sort_data%';

+--------------------------+-------+
| Variable_name | Value |
+--------------------------+-------+
| max_length_for_sort_data | 1024 |
+--------------------------+-------+
經過筆者測試,如果排序查詢的資料兩大於這個預設值的話,還是會使用Using filesort。

總結一句,當排序查詢的資料量在預設值的範圍內是,在排序的欄位上加上索引可以提升MySQL查詢的速度。

本文永久更新連結地址:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.