首页 > 解决方案 > 使用带有“IN 子句”和“=”的查询

问题描述

需要建议,因为由于性能改进,我需要将所有循环查询转换为 IN 子句。我有以下可能因迭代而异的条件..

Where recordID=2323 and (origin=626 or destination=319);
Where recordID=2323 and (origin=319 or destination=789);
Where recordID=2323 and (origin=567 or destination=989);
Where recordID=2323 and (origin=767 or destination=626);

为了提高性能,我想像这样将这些查询转换为 IN 子句。

  Where recordID=2323 and (origin IN(626,319,567,767) or destination IN (319, 789, 989, 626));

我的问题是两种方法的结果计数是否相同?是否有任何其他方法或任何其他方式来做到这一点。

问题是我的最终计数与每种方法相比并不相似。

标签: mysqlsqlselectin-clause

解决方案


不幸的是,没有很好的方法来优化具有or不同列上的条件的查询。如果查询很简单,您可以使用union all

select t.*
from t
where recordID = 2323 and origin = 626
union all
select t.*
from t
where recordID = 2323 and destination = 319 and origin <> 626;

然后,此版本的查询可以使用两个索引:

  • (recordID, origin)
  • (recordID, destination, origin)

编辑:

如果您不关心性能,那么您的方法in很好 - 并且等同于您的原始逻辑。


推荐阅读