MySQL我想进一步优化它

时间:2010-10-04 06:01:48

标签: database mysql query-optimization

所以我开始讨论这个问题:

SELECT * FROM TABLE1 WHERE hash IN (SELECT id FROM temptable);

花了很长时间,所以我做了一个解释:

mysql> explain SELECT * FROM TABLE1 WHERE hash IN (SELECT id FROM temptable);
+----+--------------------+-----------------+------+---------------+------+---------+------+------------+-------------+
| id | select_type        | table           | type | possible_keys | key  | key_len | ref  | rows       | Extra       |
+----+--------------------+-----------------+------+---------------+------+---------+------+------------+-------------+
|  1 | PRIMARY            | TABLE1          | ALL  | NULL          | NULL | NULL    | NULL | 2554388553 | Using where | 
|  2 | DEPENDENT SUBQUERY | temptable       | ALL  | NULL          | NULL | NULL    | NULL |       1506 | Using where | 
+----+--------------------+-----------------+------+---------------+------+---------+------+------------+-------------+
2 rows in set (0.01 sec)

它没有使用索引。所以,我的第二遍:

mysql> explain SELECT * FROM TABLE1 JOIN temptable ON TABLE1.hash=temptable.hash;
+----+-------------+-----------------+------+---------------+----------+---------+------------------------+------+-------------+
| id | select_type | table           | type | possible_keys | key      | key_len | ref                    | rows | Extra       |
+----+-------------+-----------------+------+---------------+----------+---------+------------------------+------+-------------+
|  1 | SIMPLE      | temptable       | ALL  | hash          | NULL     | NULL    | NULL                   | 1506 |             | 
|  1 | SIMPLE      | TABLE1          | ref  | hash          | hash     | 5       | testdb.temptable.hash  |  527 | Using where | 
+----+-------------+-----------------+------+---------------+----------+---------+------------------------+------+-------------+
2 rows in set (0.00 sec)

我可以进行任何其他优化吗?

1 个答案:

答案 0 :(得分:1)

使用covering index可以获得更多速度,但需要额外的空间消耗。覆盖索引是可以满足查询中所有请求的列而不执行对聚簇索引的进一步查找的索引。

首先摆脱SELECT *并明确选择您需要的字段。然后,您可以将SELECT子句中的所有字段添加到复合索引的右侧。例如,如果您的查询如下所示:

SELECT  first_name, last_name, age 
FROM    table1 
JOIN    temptable ON table1.hash = temptable.hash;

然后你可以有一个看起来像这样的覆盖索引:

CREATE INDEX ix_index ON table1 (hash, first_name, last_name, age);