我正在尝试订购并使用索引,但它似乎仍在使用filesort
表
CREATE TABLE `teachers` (
`id` int(10) unsigned NOT NULL,
`name` VARCHAR(10) NOT NULL,
`lastName` tinytext NOT NULL,
KEY `lastName` (lastName(10))
)
查询
mysql> EXPLAIN SELECT name,lastName FROM teachers ORDER BY lastName DESC;
+----+-------------+----------+------+---------------+------+---------+------+------+----------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+----------+------+---------------+------+---------+------+------+----------------+
| 1 | SIMPLE | teachers | ALL | NULL | NULL | NULL | NULL | 1546 | Using filesort |
+----+-------------+----------+------+---------------+------+---------+------+------+----------------+
答案 0 :(得分:0)
您需要创建覆盖索引last name, name
CREATE TABLE `teachers` (
`id` int(10) unsigned NOT NULL,
`name` varchar(10) NOT NULL,
`lastName` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
KEY `last_first` (`lastName`,`name`)
)
现在查询
EXPLAIN SELECT `name`, lastName FROM teachers ORDER BY lastName DESC;
产生以下结果
+----+-------------+----------+-------+---------------+------------+---------+------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+----------+-------+---------------+------------+---------+------+------+-------------+
| 1 | SIMPLE | teachers | index | NULL | last_first | 269 | NULL | 1 | Using index |
+----+-------------+----------+-------+---------------+------------+---------+------+------+-------------+
答案 1 :(得分:0)
您的问题在关键定义中: KEY lastName
(lastName(10))
特别是你在这里定义了一个KEY长度
索引仅在ORDER BY子句中命名的列的前缀。在这种情况下,索引不能用于完全解析排序顺序。例如,如果您有一个CHAR(20)列,但仅索引前10个字节,则索引无法区分超过第10个字节的值,并且需要 filesort 。
您可以写 KEY lastName
(lastName),它可以根据需要使用。