tags:

views:

369

answers:

1

I have two tables, TableA and 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

Here's my query:

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

Here's the problem:

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 |
+----+-------------+--------------+--------+---------------+---------+---------+------------------------------------------+------+-------------+

Is there an index that I can add that will prevent the full table scan of TableB?

+2  A: 

Runcible, your query could use some rewriting. You should always specify your JOIN conditions in an ON clause and not in a WHERE.

Your query would become:

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

Not only do you want to do this:

ALTER TABLE TableB ADD INDEX (shared_id,bar);

You'll want to add an index to A as follows:

ALTER TABLE TableA ADD INDEX (foo, shared_id);

Do this, and provide the EXPLAIN output please.

Also note that by adding an index on (shared_id, bar) you just made your (shared_id) index redundant. Drop it.

hobodave
Adding the second index did the trick. @hobodave: Thanks for your help!
Runcible