0

以下のようなテーブルがに対してid, positionで複合indexを追加します。

+------+----------+
| id   | position |
+------+----------+
|    1 |        1 |
|    2 |        2 |
|    3 |        5 |
|    4 |        4 |
+------+----------+

show index from test;
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| test  |          1 | idx      |            1 | id          | A         |           4 |     NULL | NULL   | YES  | BTREE      |         |               |
| test  |          1 | idx      |            2 | position    | A         |           4 |     NULL | NULL   | YES  | BTREE      |         |               |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

この状態で以下のようなクエリを発行すると複合indexが使われているように見えますがfilesortが発生してしまいます。なぜfilesortが発生してしまうのでしょうか?また、filesortを回避する方法はありますでしょうか?

mysql> explain
    -> select
    ->   *
    -> from
    ->   test
    -> where
    ->   id in (1,3,4)
    -> order by position;
+----+-------------+-------+-------+---------------+------+---------+------+------+------------------------------------------+
| id | select_type | table | type  | possible_keys | key  | key_len | ref  | rows | Extra                                    |
+----+-------------+-------+-------+---------------+------+---------+------+------+------------------------------------------+
|  1 | SIMPLE      | test  | range | idx           | idx  | 5       | NULL |    3 | Using where; Using index; Using filesort |
+----+-------------+-------+-------+---------------+------+---------+------+------+------------------------------------------+

1 件の回答 1

1

複合indexのidxid順でソートした上で重複した部分についてのみposition順でソートされているのではないでしょうか。ですのでorder by positionを実現するにはソートせざるを得ないです。

idxid, positionの順を逆転させてposition, idにすればソートは不要になりますが、今度はwhere id in (1,3,4)の検索に使えなくなってしまい本末転倒です。ですのでソートは必須と思います。

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。