简体   繁体   English

使用带有“IN 子句”与“=”的查询

[英]Using query with "IN clause" vs "="

Need suggestion as due to performance improvement i need to convert all loop queries to IN clause.由于性能改进需要建议,我需要将所有循环查询转换为 IN 子句。 I have following where conditions which may vary based on iteration..我有以下 where 条件可能因迭代而异..

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);

For performacne improvement i want to convert those queries to IN Clause like this..为了提高性能,我想将这些查询转换为这样的 IN 子句。

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

My question is the results count from both approach will be the same?我的问题是两种方法的结果计数是否相同? Is there any other approach or any other way to do this.有没有其他方法或任何其他方式来做到这一点。

Problem is my final count is not samilar compare to each approach.问题是我的最终计数与每种方法相比并不相似。

Unfortunately, there is not great way to optimize queries with or conditions on different columns.不幸的是,没有很好的方法来优化不同列上的查询or条件。 If the query is simple, you can use union all :如果查询很简单,您可以使用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;

This version of the query can then make use of two indexes:这个版本的查询然后可以使用两个索引:

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

EDIT:编辑:

If you don't care about performance, then your method with in is fine -- and equivalent to your original logic.如果您不关心性能,那么您使用in的方法就可以了——并且等同于您的原始逻辑。

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

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