简体   繁体   English

带有OR语句的mysql返回全表扫描

[英]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). 一个解释将表明它正在对表1(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. 我知道我可以将其拆分为2并使用并集,但是我宁愿不这样做,因为我的实际查询要比这个大得多,所以请建议其他方法。

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. 尝试在ON子句中而不是WHERE中指定条件。如果还没有索引,请在JOIN列上添加索引。最后,全表扫描并不总是最糟糕的选择。

ALTER TABLE Table2 ADD INDEX (field1 , field3 );

This might also speed things up. 这也可能加快速度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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