程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> MYSQL數據庫 >> MySQL綜合教程 >> MySQL優化order by導致的 using filesort,orderfilesort

MySQL優化order by導致的 using filesort,orderfilesort

編輯:MySQL綜合教程

MySQL優化order by導致的 using filesort,orderfilesort


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

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved