SQL 中的 AND 逻辑谓词逻辑

问题描述

我有 3 种类型的发票,INNU、INN1、INN2。 我试图过滤掉“INN1”和“未付”发票(我不想要 INN1 未付发票)。 我尝试使用以下条件,但它取出了所有“未付”发票。

 where [Invoice Class] IN (@invoice) 
 and ( invoice_cl <> 'INN1' and [Payment Status] <> 'Unpaid')

但后来我改变了条件并使用了以下内容并得到了正确的结果。

[Invoice Class] IN (@invoice) 
and not (invoice_cl in('INN1') and [Payment Status] = 'Unpaid')

谁能最终告诉我这两个条件之间的区别是什么。第一个条件没有按预期工作,但第二个条件给了我正确的结果。

解决方法

在第一种情况下:

where [Invoice Class] IN (@invoice) and ( invoice_cl <> 'INN1' and [Payment Status] <> 'Unpaid')

括号没有任何作用。这相当于:

where [Invoice Class] IN (@invoice) and invoice_cl <> 'INN1' and [Payment Status] <> 'Unpaid'

这样就可以过滤掉所有“未付”发票。

在第二个示例中,由于 not 在括号之外,因此分组很重要。

[Invoice Class] IN (@invoice) and not (invoice_cl in('INN1') and [Payment Status] = 'Unpaid')

这会过滤掉两个条件都满足的记录,而不是所有其中一个条件都满足的记录。