-1

我正在尝试按索引排序并使用索引,但它似乎仍在使用文件排序

桌子

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 |
+----+-------------+----------+------+---------------+------+---------+------+------+----------------+
4

2 回答 2

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 |
+----+-------------+----------+-------+---------------+------------+---------+------+------+-------------+
于 2013-02-10T08:46:47.417 回答
0

您的问题在于键定义:KEY lastName(lastName(10))

特别是您在这里定义了一个 KEY 长度

您只索引在 ORDER BY 子句中命名的列的前缀。在这种情况下,索引不能用于完全解析排序顺序。例如,如果您有一个 CHAR(20) 列,但仅索引前 10 个字节,则索引无法区分超过第 10 个字节的值,因此需要进行文件排序。

证明链接

您可以编写KEY lastName(lastName),它会根据您的需要工作。

于 2013-12-23T11:38:12.610 回答