【问题标题】:MySQL query uses filesort despite index when ordering尽管排序时有索引,但 MySQL 查询使用文件排序
【发布时间】: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, ASCDESC, DESC排序,不可混用。
  • 我试过按 "date, col_2 desc" 和 "col_2, date desc" 排序,结果是一样的。
  • 如果您的索引是(col_2, date),请尝试ORDER BY col_2 DESC, date DESC

标签: mysql sql join indexing


【解决方案1】:

答案是按照您创建索引的相同顺序对结果进行排序..e.g. 如果索引是 (col_1, col_2) 则使用 ... order by col_1 desc, col_2 desc... order by col_1 asc, col_2 asc 而不是 ... order by col_1 asc, col_2 descorder by col_2, col_1 例如。

【讨论】:

    猜你喜欢
    • 2012-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多