简体   繁体   English

SQL中的多个IN子句

[英]Multiple IN Clauses in SQL

I'm not sure about the functionality of the IN clause so I want to know if I can run a query safely. 我不确定IN子句的功能,因此我想知道是否可以安全地运行查询。 For what I understand when using IN clause in SQL Server creates a series of OR statements: So for example 据我了解,在SQL Server中使用IN子句时会创建一系列OR语句:例如

SELECT * FROM table WHERE column IN (1, 2, 3, 4, 5, 6)

Will be the same that: 将与以下相同:

SELECT * FROM table WHERE column = 1 OR column = 2 OR column = 3 OR column = 4 OR column = 5 OR column = 6

But what happens when something like this is executed: 但是,当执行这样的操作时会发生什么:

SELECT * FROM table WHERE column IN (1, 2, 3) and column2 IN (4,5,6) and column 3 IN (5,7,8)

Here I want to know if for example, if some value from the first IN has two occurrences within the second one it will retrieve both results, or if it's executed in order like 1 and 4 and 5 (The first value within the IN clauses) 在这里我想知道,例如,如果第一个IN中的某个值在第二个IN中有两次出现,它将检索两个结果,还是按1、4和5的顺序执行(IN子句中的第一个值)

I want to run a query with 8 parameters that I need to check in the DB (Sending by C#) but I don't want to build a super huge query with a lot of OR like this (because it will be +90k records) 我想用8个参数运行查询,需要在数据库中检查(通过C#发送),但我不想用很多OR这样构建一个超大型查询(因为它将是+ 90k记录)

 SELECT * FROM table WHERE (column = 1 and column2 = 4 and column3 = 5 ) or 
(column = 2 and column2= 5 and column3 = 7) OR ....

Or I don't know if there is a better approach to solve this, I'm open to ideas. 或者我不知道是否有更好的方法来解决此问题,我愿意接受想法。

Thanks 谢谢

The IN s are separate conditions, so the logic is equivalent to: IN是独立的条件,因此逻辑等效于:

where (column1 = 1 or column1 = 2 or column1 = 3) and
      (column2 = 4 or column2 = 5 or column2 = 6)

Note that this is a logical equivalence. 注意,这是逻辑上的对等。 Some databases optimize IN with constant lists, for instance, by creating a binary tree for searching the values. 例如,某些数据库通过创建用于搜索值的二叉树来使用常量列表优化IN I don't think that SQL Server does such an optimization though. 我不认为SQL Server会进行这种优化。

If you want "alignment", some databases -- but not SQL Server -- support tuples using IN : 如果要“对齐”,则某些数据库(而不是SQL Server)支持使用IN元组:

where (column1, column2) in ( (1, 4), (2, 5), (3, 5) )

And this can always be represented as: 这总是可以表示为:

where (column1 = 1 and column2 = 4) or
      (column1 = 2 and column2 = 5) or
      (column1 = 3 and column2 = 6)

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

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