如何在进行简单的JOIN时阻止全表扫描?

时间:2009-07-29 23:52:07

标签: mysql join

我有两个表,TableA和TableB:

CREATE TABLE `TableA` (
  `shared_id` int(10) unsigned NOT NULL default '0',
  `foo` int(10) unsigned NOT NULL,
  PRIMARY KEY  (`shared_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1


CREATE TABLE `TableB` (
  `shared_id` int(10) unsigned NOT NULL auto_increment,
  `bar` int(10) unsigned NOT NULL,
  KEY `shared_id` (`shared_id`)
) ENGINE=MyISAM AUTO_INCREMENT=1001 DEFAULT CHARSET=latin1 

以下是我的问题:

SELECT TableB.bar 
FROM TableB, TableA 
WHERE TableA.foo = 1000 
AND TableA.shared_id = TableB.shared_id;

问题在于:

mysql> explain SELECT TableB.bar FROM TableB, TableA WHERE TableA.foo = 1000 AND TableA.shared_id = TableB.shared_id;

+----+-------------+--------------+--------+---------------+---------+---------+------------------------------------------+------+-------------+
| id | select_type | table        | type   | possible_keys | key     | key_len | ref                                      | rows | Extra       |
+----+-------------+--------------+--------+---------------+---------+---------+------------------------------------------+------+-------------+
|  1 | SIMPLE      | TableB       | ALL    | shared_id     | NULL    | NULL    | NULL                                     | 1000 |             |
|  1 | SIMPLE      | TableA       | eq_ref | PRIMARY       | PRIMARY | 4       | MyDatabase.TableB.shared_id              |    1 | Using where |
+----+-------------+--------------+--------+---------------+---------+---------+------------------------------------------+------+-------------+

是否有可以添加的索引会阻止TableB的全表扫描?

1 个答案:

答案 0 :(得分:2)

Runcible,您的查询可能会使用一些重写。您应该始终在ON子句中而不是在WHERE中指定JOIN条件。

您的查询将变为:

SELECT TableB.bar 
FROM TableB
JOIN TableA
ON TableB.shared_id = TableA.shared_id
AND TableA.foo = 1000;

您不仅想要这样做:

ALTER TABLE TableB ADD INDEX (shared_id,bar);

您需要按如下方式向A添加索引:

ALTER TABLE TableA ADD INDEX (foo, shared_id);

请执行此操作,并提供EXPLAIN输出。

另请注意,通过在(shared_id,bar)上添加索引,您只需使(shared_id)索引冗余。放弃它。