为什么AND在SQL中的AND IN子句不起作用

时间:2019-02-08 16:29:33

标签: sql-server tsql

如果我输入

Select * 
from MyTable 
where LoanNumber = 12345 and LoanNumber = 546787;

这什么都不返回。

但是如果我输入

Select * 
from MyTable
where LoanNumber in (12345, 546787) 

它返回两行。为什么会这样?

3 个答案:

答案 0 :(得分:3)

这是因为评估是逐行进行的。行不能有2个不同的值。不能同时位于同一行中的12345 546787

如果将AND更改为OR,它将返回与使用IN相同的结果。

答案 1 :(得分:2)

您的行可能看起来像

id   loannumber   other columns
--   ----------   -------------
1    12345        etc...
2    546787       more etc...
...

撰写时

Select * 
from MyTable 
where LoanNumber = 12345 and LoanNumber =546787;

您指示sql server查找这样的每一行

for every row in MyTable
  does this row have value 12345 in LoanNumber
  and does this row also have value 546787 in LoanNumber
  If both condtions are true then return this row

两个条件都必须为真(因为您编写了AND),并且这当然是不可能的

撰写时

Select * 
from MyTable 
where LoanNumber = 12345 OR LoanNumber =546787;

Select * 
from MyTable 
where LoanNumber in (12345, 546787);

您指示sql server查找这样的每一行

 for every row in MyTable  
   does this row have value 12345 in LoanNumber  
   if not, then does this row have value 546787 in LoanNumber  
   If ONE of the condtions are true then return this row  

只有一个条件必须为真(因为您写的是OR或IN)

如评论和其他答案中所述,数据库将连续进行比较。

答案 2 :(得分:0)

IN表示LoanNumber等于指定的任何值。
从逻辑上讲,它是 OR 而不是 AND