为什么MySQL不使用“查询”子查询中的索引?

时间:2014-06-11 20:16:54

标签: mysql mysqldump

如果我运行简单的查询,它会很快完成:

explain select * from my_data where id in (132730151);
+----+-------------+---------+-------+---------------+---------+---------+-------+------+-------+
| id | select_type | table   | type  | possible_keys | key     | key_len | ref   | rows | Extra |
+----+-------------+---------+-------+---------------+---------+---------+-------+------+-------+
|  1 | SIMPLE      | my_data | const | PRIMARY       | PRIMARY | 4       | const |    1 |       |
+----+-------------+---------+-------+---------------+---------+---------+-------+------+-------+

如果我使用子查询运行基本相同的查询,它似乎永远不会完成:

explain select * from my_data where id in (select my_data_id from my_other_data where id = 46855459);
+----+--------------------+---------------+-------+--------------------------+---------+---------+-------+-----------+-------------+
| id | select_type        | table         | type  | possible_keys            | key     | key_len | ref   | rows      | Extra       |
+----+--------------------+---------------+-------+--------------------------+---------+---------+-------+-----------+-------------+
|  1 | PRIMARY            | my_data       | ALL   | NULL                     | NULL    | NULL    | NULL  | 132862517 | Using where |
|  2 | DEPENDENT SUBQUERY | my_other_data | const | PRIMARY,my_data_id_index | PRIMARY | 4       | const |         1 |             |
+----+--------------------+---------------+-------+--------------------------+---------+---------+-------+-----------+-------------+

对于这种情况,似乎MySQL正在经历每一行。为什么没有mysql在第二种情况下使用id的主索引?

我的例子有点做作。我实际上使用mysqldump导出一系列数据,这是最简单的情况。由于我使用mysqldump,我无法将其转换为连接,因为我只能访问where子句。

0 个答案:

没有答案