简体   繁体   中英

mysql with OR statement returns full table scan

So I have this query

SELECT
  *
FROM table1 i
  LEFT JOIN table2 k
    ON k.field1 = i.field2
WHERE  k.field3 IN
                   (632569, 658869, 1253996, 2112571, 164715, 165082, 658665, 180550, 323455, 165579, 164665, 282091, 164605, 164714, 626888, 165277, 164196)
                    OR i.field2
                     IN
                      (632569, 658869, 1253996, 2112571, 164715, 165082, 658665, 180550, 323455, 165579, 164665, 282091, 164605, 164714, 626888, 165277, 164196);

An explain would reveal that it's performing full table scan on table1 (i). Is there a way to reform the query so that it won't do a full table scan?

I know that I can split it into 2 and use union, but I would rather not do it since my actual query is much bigger than this, so please suggest alternate methods.

SELECT
  *
FROM table1 i
  LEFT JOIN table2 k
    ON k.field1 = i.field2
WHERE EXISTS (subquery)

Do you want something like that? Watch out for null values!!

SELECT
  *
FROM table1 i
  LEFT JOIN table2 k
    ON k.field1 = i.field2 AND  k.field3 IN
                   (632569, 658869, 1253996, 2112571, 164715, 165082, 658665, 180550, 323455, 165579, 164665, 282091, 164605, 164714, 626888, 165277, 164196)
    OR i.field2 IN
                   (632569, 658869, 1253996, 2112571, 164715, 165082, 658665, 180550, 323455, 165579, 164665, 282091, 164605, 164714, 626888, 165277, 164196);

Try to specify your conditions in the ON clause and not in WHERE.Also add indexes on the JOIN columns if they are not there already.An ending note,full table scans are not always the worst option.

ALTER TABLE Table2 ADD INDEX (field1 , field3 );

This might also speed things up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM