这是我的表:
CREATE TABLE `person` (
`id` bigint(10) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`age` int(10) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `age` (`age`)
) ENGINE=InnoDB AUTO_INCREMENT=10000 DEFAULT CHARSET=latin1;
这是解释的输出:
mysql> explain select * from person order by age\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: person
type: ALL
possible_keys: NULL
key: NULL
key_len: NULL
ref: NULL
rows: 10367
Extra: Using filesort
1 row in set (0.00 sec)
这是怎么回事?为什么 MySQL 不使用age
索引进行排序?我试过 doind analyze table
,但没有任何区别。
仅供参考,以下是表中数据的分布:
mysql> select age, count(*) from person group by age;
+-----+----------+
| age | count(*) |
+-----+----------+
| 21 | 1250 |
| 22 | 1216 |
| 23 | 1278 |
| 24 | 1262 |
| 25 | 1263 |
| 26 | 1221 |
| 27 | 1239 |
| 28 | 1270 |
+-----+----------+
8 rows in set (0.04 sec)
更新
@grisha 似乎认为您不能选择不在索引中的字段。这似乎没有任何意义,但是,它看起来像以下作品:
mysql> explain select age from person order by age \G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: person
type: index
possible_keys: NULL
key: age
key_len: 4
ref: NULL
rows: 10367
Extra: Using index
1 row in set (0.00 sec)
而且,如果我添加一个涵盖所有字段的索引,它也可以工作:
mysql> alter table person add key `idx1` (`age`, `id`, `name`);
Query OK, 0 rows affected (0.29 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> explain select * from person order by age\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: person
type: index
possible_keys: NULL
key: idx1
key_len: 35
ref: NULL
rows: 10367
Extra: Using index
1 row in set (0.00 sec)
@eggyal 建议使用索引提示。这似乎也有效,并且可能是正确的答案:
mysql> explain select * from person force key for order by (age) order by age\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: person
type: index
possible_keys: NULL
key: age
key_len: 4
ref: NULL
rows: 10367
Extra:
1 row in set (0.02 sec)