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 僅讀取所需行。
SHOW VARIABLES LIKE 'max_length_for_sort_data';
+--------------------------+-------+
| Variable_name | Value |
+--------------------------+-------+
| max_length_for_sort_data | 1024 |
若排序行長度超過此值(默認 1024 字節),MySQL 仍會使用 filesort(磁盤臨時表),即使有索引。解決:
SELECT *)ORDER BY 列加索引可消除 filesortLIMIT 效果最佳(索引順序讀取前 N 行)max_length_for_sort_data 限制,選列優化同等重要