MySQL未按预期使用索引

时间:2018-06-22 11:45:46

标签: mysql indexing subquery

EXPLAIN关于此查询

select v.type,sum(c.rank)
from
  (select distinct power,color,type from vehicle) v
  join configuration c using (power,color)
group by v.type

给予

+----+-------------+---------------+------------+-------+---------------+-------------+---------+-----------------------------------------+---------+----------+---------------------------------+
| id | select_type |     table     | partitions | type  | possible_keys |     key     | key_len |                   ref                   |  rows   | filtered |              Extra              |
+----+-------------+---------------+------------+-------+---------------+-------------+---------+-----------------------------------------+---------+----------+---------------------------------+
|  1 | PRIMARY     | configuration | NULL       | ALL   | veh           | NULL        | NULL    | NULL                                    |   76658 |   100.00 | Using temporary; Using filesort |
|  1 | PRIMARY     | <derived2>    | NULL       | ref   | <auto_key0>   | <auto_key0> | 6       | configuration.power,configuration.color |      65 |   100.00 | NULL                            |
|  2 | DERIVED     | vehicle       | NULL       | index | cov           | cov         | 20      | NULL                                    | 5058658 |   100.00 | Using index                     |
+----+-------------+---------------+------------+-------+---------------+-------------+---------+-----------------------------------------+---------+----------+---------------------------------+

即使我设置了force index

,也不会使用配置索引(电源,颜色)

如果我使用表而不是子查询

create table tmp select distinct power,color,type from vehicle

然后在“相同”查询上Explain

select v.type,sum(c.rank)
from
  tmp v 
  join configuration c using (power,color)
group by type

成为

+----+-------------+---------------+------------+------+---------------+------+---------+---------------------+---------+----------+---------------------------------+
| id | select_type |     table     | partitions | type | possible_keys | key  | key_len |         ref         |  rows   | filtered |              Extra              |
+----+-------------+---------------+------------+------+---------------+------+---------+---------------------+---------+----------+---------------------------------+
|  1 | SIMPLE      | tmp           | NULL       | ALL  | NULL          | NULL | NULL    | NULL                | 1016144 |   100.00 | Using temporary; Using filesort |
|  1 | SIMPLE      | configuration | NULL       | ref  | veh           | veh  | 6       | tmp.power,tmp.color |       2 |   100.00 | NULL                            |
+----+-------------+---------------+------------+------+---------------+------+---------+---------------------+---------+----------+---------------------------------+

这快4倍

如何避免使用硬表?

1 个答案:

答案 0 :(得分:2)

在第一种情况下,优化器认为最好通过使用派生表中的自动生成的键来执行此操作。

在第二种情况下,临时表中没有密钥,因此最好的计划是先进行tmp。

您应该能够通过使用STRAIGHT_JOIN而不是JOIN来强制表顺序。