I have a query that has 3 left joins on it from other tables, i'll write an example below (MySQL 5.1.32)..
(All conditions are key'd)
SELECT tb1.*, tb2.*, tb3.* tb4.*
FROM tb1
LEFT JOIN tb2
ON tb1.col = tb2.col
LEFT JOIN tb3
ON tb3.col = tb1.col
LEFT JOIN tb4
ON tb4.col = tb1.col
WHERE tb1.col1 = value OR tb1.col2 = value OR tb1.col3 = value
ORDER BY tb1.col4 ASC
The problem is that because I use an OR in the where clause, it does a full table scan, so I wondered if doing this within a union would be faster?
Example:
(
SELECT tb1.*, tb2.*, tb3.* tb4.*
FROM tb1
LEFT JOIN tb2
ON tb1.col = tb2.col
LEFT JOIN tb3
ON tb3.col = tb1.col
LEFT JOIN tb4
ON tb4.col = tb1.col
WHERE tb1.col1 = value
)
UNION ALL
(
SELECT tb1.*, tb2.*, tb3.* tb4.*
FROM tb1
LEFT JOIN tb2
ON tb1.col = tb2.col
LEFT JOIN tb3
ON tb3.col = tb1.col
LEFT JOIN tb4
ON tb4.col = tb1.col
WHERE tb1.col2 = value
)
UNION ALL
(
SELECT tb1.*, tb2.*, tb3.* tb4.*
FROM tb1
LEFT JOIN tb2
ON tb1.col = tb2.col
LEFT JOIN tb3
ON tb3.col = tb1.col
LEFT JOIN tb4
ON tb4.col = tb1.col
WHERE tb1.col3 = value
)
This way instead of using the OR value, each where condition went inside of it's own union, the thing that I'm confused about is that the first time I ran this it came up with 0.04 sec time, on a small table, whereas the first one showed at 0.00 sec, but all of the 'types' on the union showed as either ref or eq_ref which isn't a full scan, except for the union result select_type.
So I was wondering if anyone could explain this to me and point me in the right direction please.