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查詢的速度。
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com