1. 程式人生 > >MySQL優化order by導致的 using filesort

MySQL優化order by導致的 using filesort

from 永久 idc SM 大於 xid 圖片 sele style

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查詢的速度。

本文永久更新鏈接地址:http://www.linuxidc.com/Linux/2015-11/124881.htm

技術分享圖片

MySQL優化order by導致的 using filesort