小编典典

SQL逻辑运算符优先级:And and Or

sql

下面的两个语句是否等效?

SELECT [...]
FROM [...]
WHERE some_col in (1,2,3,4,5) AND some_other_expr

SELECT [...]
FROM [...]
WHERE some_col in (1,2,3) or some_col in (4,5) AND some_other_expr

我可以使用某种真值表来验证这一点吗?


阅读 515

收藏
2021-04-16

共1个答案

小编典典

And优先于Or,因此,即使a <=> a1 Or a2

Where a And b 

与…不同

Where a1 Or a2 And b,

因为那将被执行为

Where a1 Or (a2 And b)

并且想要使它们相同,是以下内容(使用括号覆盖优先级规则):

 Where (a1 Or a2) And b

这是一个示例说明:

Declare @x tinyInt = 1
Declare @y tinyInt = 0
Declare @z tinyInt = 0

Select Case When @x=1 OR @y=1 And @z=1 Then 'T' Else 'F' End -- outputs T
Select Case When (@x=1 OR @y=1) And @z=1 Then 'T' Else 'F' End -- outputs F
2021-04-16