これは私が持っているテーブルです:
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;
これは Explain の出力です。
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)