MySQL 查询在排序时使用文件排序,尽管有索引

标签 mysql sql join indexing

编辑: 我使查询更简单只是为了测试:

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 会使用文件排序?我该如何防止它?

最佳答案

答案是按照您创建索引的相同顺序对结果进行排序……例如 如果索引是 (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 desc or order by col_2, col_1 例如。

关于MySQL 查询在排序时使用文件排序,尽管有索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13516440/

相关文章:

php - 回显 SELECT 语句中的变量

mysql - col 查询结果中有重复字段

python - 按属性值对对象进行排序且不允许出现间隙或重复的算法

sql - 为什么执行存储过程比脚本中的 SQL 查询更快?

MySQL JOIN : Select a row if a bool column is 1, 否则选择第一行

sql - 如何多次使用特定列连接两个表

mysql - 依靠工作历史日志

mysql - Visual Studio : Create Entity Data Model with remote Mysql database

mysql - xlsx到mysql数据的字符编码问题

mysql - 根据关键字获得最高值(value)