优化MySQL自连接查询

时间:2014-04-14 13:45:16

标签: mysql

我有以下查询:

SELECT DISTINCT(a1.actor) 
FROM actions a1 
JOIN actions a2 ON a1.ip = a2.ip 
WHERE a2.actor = 143 
AND a2.ip != '0.0.0.0' 
AND a2.ip != '' 
AND a2.actor != a1.actor 
AND a1.actor != 0

这是查询的解释:

+----+-------------+-------+-------+------------------+---------+---------+------------------+------+--------------------------+
| id | select_type | table | type  | possible_keys    | key     | key_len | ref              | rows | Extra                    |
+----+-------------+-------+-------+------------------+---------+---------+------------------+------+--------------------------+
|  1 | SIMPLE      | a2    | range | actor,ip,actorIp | actorIp | 66      | NULL             | 3800 | Using where; Using index |
|  1 | SIMPLE      | a1    | ref   | ip               | ip      | 62      | formabilio.a2.ip |   11 | Using where              |
+----+-------------+-------+-------+------------------+---------+---------+------------------+------+--------------------------+

即使从这看起来它似乎不是一个有问题的查询,在我的机器中,MyIsam需要或多或少69秒,而InnoDB需要56秒。该表有大约1千条记录。正如你从解释中看到的那样,我在actor列,ip列甚至两列都有变量。我有mysql版本5.5.35。

你知道为什么这个查询花了这么长时间吗?我该如何优化呢?

2 个答案:

答案 0 :(得分:0)

表SCAN正在执行表操作的每个记录。

根据本教程: http://www.mysqltutorial.org/mysql-self-join/

SELECT DISTINCT(a1.actor)
FROM actions a1
INNER JOIN actions a2 
ON a1.ip = a2.ip AND
   a1.actor <> a2.actor
WHERE a2.actor = 143 
AND a2.ip <> '0.0.0.0' 
AND a2.ip <> ''
AND a1.actor <> 0

答案 1 :(得分:-1)

尝试这个(如果你还没有这样做)......下面的命令应该在join-field和some-conditions

上创建索引
CREATE INDEX _actions_ip ON actions( ip );
CREATE INDEX _actions_actor ON actions( actor );