5

これは私が持っているテーブルです:

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

1 に答える 1

3

インデックス列のみを選択すると、インデックスがソートに役立ちます。あなたの場合は を選択する*ため、mysqlインデックスは使用しません。

通常、インデックスが並べ替えに役立たないのはなぜですか?

index on を使用しtてフィールドごとにテーブルを並べ替えたい場合は、次のようにします。my_fieldmy_field

for each my_field f in index, do :
    get all records where my_field = f and add to result
return result

クラスター化されたインデックスではないと仮定すると、上記は t の行数と同じ数のランダム I/O を実行しますが (膨大になる可能性があります)、単純な外部ソートアルゴリズムはブロック/ページ単位でデータを順次読み取り、実行するランダム I/O ははるかに少なくなります。 Oさん。

したがって、もちろん db に「インデックスを使用してソートを行いたい」と言うことができますが、それは実際には効率的ではありません。

于 2012-11-12T11:54:25.570 に答える