MySQL索引 - In vs. Equals索引问题

时间:2014-03-03 14:41:22

标签: mysql sql innodb

以下查询在mysql服务器上运行得相当快:

SELECT  table_name.id 
FROM table_name 
WHERE table_name.id in (10000)

SELECT table_name.id 
from table_name 
where table_name.id = (SELECT table_name.id 
                       FROM table_name 
                       WHERE table_name.id in (10000)
                      );

但如果我将第二个查询更改为如下,则需要超过20秒:

SELECT table_name.id 
from table_name 
where table_name.id in (SELECT table_name.id 
                        FROM table_name 
                        WHERE table_name.id in (10000)
                        );

在做解释时,我得到以下输出。很明显,关于MySQL如何索引数据存在一些问题,并在关键字中使用。

首次查询:

+----+-------------+---------------+-------+---------------+---------+---------+-------+------+-------------+
| id | select_type | table         | type  | possible_keys | key     | key_len | ref   | rows | Extra       |
+----+-------------+---------------+-------+---------------+---------+---------+-------+------+-------------+
|  1 | SIMPLE      | table_name    | const | PRIMARY       | PRIMARY | 4       | const |    1 | Using index |
+----+-------------+---------------+-------+---------------+---------+---------+-------+------+-------------+

第二次查询:

+----+-------------+---------------+-------+---------------+---------+---------+-------+------+-------------+
| id | select_type | table         | type  | possible_keys | key     | key_len | ref   | rows | Extra       |
+----+-------------+---------------+-------+---------------+---------+---------+-------+------+-------------+
|  1 | PRIMARY     | table_name    | const | PRIMARY       | PRIMARY | 4       | const |    1 | Using index |
|  2 | SUBQUERY    | table_name    | const | PRIMARY       | PRIMARY | 4       |       |    1 | Using index |
+----+-------------+---------------+-------+---------------+---------+---------+-------+------+-------------+

对于第三个查询:

+----+--------------------+------------+-------+---------------+---------+---------+-------+---------+--------------------------+
| id | select_type        | table_name | type  | possible_keys | key     | key_len | ref   | rows    | Extra                    |
+----+--------------------+------------+-------+---------------+---------+---------+-------+---------+--------------------------+
|  1 | PRIMARY            | table_name | index | NULL          | sentTo  | 5       | NULL  | 6250751 | Using where; Using index |
|  2 | DEPENDENT SUBQUERY | table_name | const | PRIMARY       | PRIMARY | 4       | const |       1 | Using index              |
+----+--------------------+------------+-------+---------------+---------+---------+-------+---------+--------------------------+

我正在使用InnoDB并尝试更改第三个查询以强制使用索引,如下所示。

1 个答案:

答案 0 :(得分:0)

在第一种情况下,你只有来自子查询的第一条记录(它运行一次,因为equals仅用于第一个值)

在第二个查询中,您获得了笛卡尔乘法(每个都有),因为IN为每一行运行子查询。这对性能不利

尝试在这些情况下使用联接。