首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 數據庫知識 >  >> MySQL 資料庫 >> MySQL 綜合教學

MySQL ORDER BY 導致 Using filesort 優化實戰:索引消除文件排序

     編輯:MySQL 綜合教學

現象

EXPLAIN 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 |
+----+-------------+----------+------+---------------+------+---------+------+---------+----------------+

優化動作

ALTER TABLE yw_syjgb ADD INDEX idx_result_date (result_date);

優化後

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

Using filesort 消失,type=index 表示全索引掃描,rows=1000 僅讀取所需行。

關鍵參數:max_length_for_sort_data

SHOW VARIABLES LIKE 'max_length_for_sort_data';
+--------------------------+-------+
| Variable_name            | Value |
+--------------------------+-------+
| max_length_for_sort_data | 1024  |

若排序行長度超過此值(默認 1024 字節),MySQL 仍會使用 filesort(磁盤臨時表),即使有索引。解決:

  • 只查必要列(避免 SELECT *)
  • 適當增大該參數(需評估內存影響)

總結

  1. ORDER BY 列加索引可消除 filesort
  2. 配合 LIMIT 效果最佳(索引順序讀取前 N 行)
  3. 注意 max_length_for_sort_data 限制,選列優化同等重要
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved