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?
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:
Not only do you want to do this:
You’ll want to add an index to A as follows:
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.