inner join on key does full table scan anyway
I discovered this in a real world scenario, but have reduced it to its essence
here. An inner join performed using only indexed fields in the "ON" clause still
results in a full table scan -- and here's the issue -- the "ON" clause contains
an "OR" keyword. Here is an example,
CREATE TABLE a ( x INT PRIMARY KEY,
y INT UNIQUE KEY );
CREATE TABLE b ( z INT PRIMARY KEY );
-- must insert a few values otherwise 'EXPLAIN' gives trivial answer
INSERT INTO a VALUES (1,2),(2,3);
INSERT INTO b VALUES (2),(3);
EXPLAIN SELECT * FROM a INNER JOIN b ON b.z = a.x OR b.z = a.y;
+----+-------------+-------+------+---------------+------+---------+------+------+------------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+------+------+------------------------------------------------+
| 1 | SIMPLE | a | ALL | PRIMARY,y | NULL | NULL | NULL | 2 | |
| 1 | SIMPLE | b | ALL | PRIMARY | NULL | NULL | NULL | 2 | Range checked for each record (index map: 0x1) |
AS you can see, this query will result in a full table scan of 'b' even though the
link in the 'ON' clause is composed of only indexed keys. If 'OR' is removed and
only one of the conditions remains, or the 'OR' is replaced by an 'AND', then the
high speed, indexed table join is achieved:
EXPLAIN SELECT * FROM a INNER JOIN b ON b.z = a.x;
+----+-------------+-------+--------+---------------+---------+---------+----------------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+--------+---------------+---------+---------+----------------+------+-------------+
| 1 | SIMPLE | a | ALL | PRIMARY | NULL | NULL | NULL | 2 | |
| 1 | SIMPLE | b | eq_ref | PRIMARY | PRIMARY | 4 | acc_rollup.a.x | 1 | Using index |
+----+-------------+-------+--------+---------------+---------+---------+----------------+------+-------------+
I know I could us a union to perform the identical select with both of the 'OR'
expressions, but that is so incredibly ugly, painful and counter intuitive.
Any thoughts?
Subject
Views
Written By
Posted
inner join on key does full table scan anyway
7460
October 26, 2007 06:34AM
3512
October 26, 2007 01:21PM
Sorry, you can't reply to this topic. It has been closed.
Content reproduced on this site is the property of the respective copyright holders.
It is not reviewed in advance by Oracle and does not necessarily represent the opinion
of Oracle or any other party.