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
是否有某种真理表可以用来验证?
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
对于喜欢查阅参考资料的人(按字母顺序):
我会加2分:
所以,2个表达式根本不相等。
WHERE some_col in (1,2,3,4,5) AND some_other_expr
--to the optimiser is this
WHERE
(
some_col = 1 OR
some_col = 2 OR
some_col = 3 OR
some_col = 4 OR
some_col = 5
)
AND
some_other_expr
所以,当你打破IN子句时,你会将串行OR分开,并改变优先级。
您可以使用括号来覆盖优先规则。
链接地址: http://www.djcxy.com/p/58891.html上一篇: SQL Logic Operator Precedence: And and Or
下一篇: PHP's =& operator