MYSQL在简单查询中使用ORDER BY索引列时使用filesort

时间:2011-09-01 14:54:27

标签: mysql indexing filesort

我见过很多类似的问题,但我没有看到一个对我有用的解决方案。或者也许我只是在密集。 :)希望有人可以帮助我。

我有下表:

CREATE TABLE `table_name` (
  `value1` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
  `value2` varchar(50) NOT NULL,
  `value3` tinytext,
  `value4` tinytext,
  `value5` tinytext,
  `value6` char(3) DEFAULT NULL,
  `value7` char(3) DEFAULT NULL,
  PRIMARY KEY (`value1`),
  KEY value2_index ('value2')
) ENGINE=MyISAM AUTO_INCREMENT=46 DEFAULT CHARSET=latin1;

要验证我的索引已设置,这是SHOW INDEX结果:

+--------------+------------+----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
| Table        | Non_unique | Key_name       | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment |
+--------------+------------+----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
| table_name   |          0 | PRIMARY        |            1 | value1      | A         |          43 |     NULL | NULL   |      | BTREE      |         |
| table_name   |          1 | value2_index   |            1 | value2      | A         |        NULL |     NULL | NULL   | YES  | BTREE      |         |
+--------------+------------+----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
2 rows in set (0.00 sec)

我正在运行此查询:

SELECT value2, value6
FROM table_name
WHERE value7 = 'Yes'
ORDER BY value2;

我想通过在value2上添加索引,它会阻止查询使用filesort。但是,EXPLAIN显示不同:

+----+-------------+--------------+------+---------------+------+---------+------+------+-----------------------------+
| id | select_type | table        | type | possible_keys | key  | key_len | ref  | rows | Extra                       |
+----+-------------+--------------+------+---------------+------+---------+------+------+-----------------------------+
|  1 | SIMPLE      | table_name   | ALL  | NULL          | NULL | NULL    | NULL |   43 | Using where; Using filesort |
+----+-------------+--------------+------+---------------+------+---------+------+------+-----------------------------+
1 row in set (0.00 sec)

我做错了什么?

谢谢!

1 个答案:

答案 0 :(得分:6)

查询首先需要查找value7 ='Yes'的行,这意味着您的索引必须包含value7作为要使用的第一列。对于那些匹配的行,需要按value2排序。因此该查询需要一个多列索引(value7,value2)。

您可以在MySQL docs中了解有关索引的更多信息。