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

标签 sql logical-operators operator-precedence

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

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

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

最佳答案

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

对于那些喜欢查阅引用资料的人(按字母顺序排列):

关于SQL 逻辑运算符优先级 : And and Or,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22078253/

相关文章:

c - 返回逻辑运算符

logical-operators - 使用 CAML <Or> 和 <And> 运算符

java - 为什么 == 在 Java 中比 postfix++ 有更高的优先级?

r - 运算符优先级是否解释了这些涉及数字与否定逻辑的乘法的表达式的差异?

java - 编写字符串评估函数

sql - Oracle sql : get only specific part of a substring

mysql - 在不更改任何字段的情况下更新时间戳的mysql表列

php - 用于查询特定类别的wp帖子的sql语句

mysql - 表中不存在键列 'courseid'

Python:按元素比较数组与 float