【发布时间】:2012-11-11 01:44:12
【问题描述】:
编辑: 我让查询变得更简单,只是为了测试:
select *
from table1 where date >= '2012-02-02' order by date, col_2 desc
我在 date 和 col_2 上有复合索引,但是当我对查询进行解释时,它显示:
+----+-------------+------------------+-------+--------------------------+-----------------+---------+------+------+-----------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+------------------+-------+--------------------------+-----------------+---------+------+------+-----------------------------+
| 1 | SIMPLE | table1 | range | col_2_date, date | col_2_date | 4 | NULL | 4643 | Using where; Using filesort |
+----+-------------+------------------+-------+--------------------------+-----------------+---------+------+------+-----------------------------+
如果我在 col_2 和 date 列上有索引,为什么 mySQL 使用文件排序?我该如何防止它?
【问题讨论】:
-
您在日期上没有索引。您还希望它如何排序? (看起来没有正确的日期列被编入索引)
-
复合索引真的是
(date, col_2),而不是顾名思义的(col_2, date)吗? -
即使使用复合索引,想要的顺序也是
date ASC, col_2 DESC。索引可用于ASC, ASC或DESC, DESC排序,不可混用。 -
我试过按 "date, col_2 desc" 和 "col_2, date desc" 排序,结果是一样的。
-
如果您的索引是
(col_2, date),请尝试ORDER BY col_2 DESC, date DESC