在SQL中,使用带有OR的括号是什么意思? [英] In SQL, what does using parentheses with an OR mean?
问题描述
示例:
select count(*) from my table
where
column1 is not null
and
(column1 = 4 OR column1 = 5)
示例2:
select count(*) from my table
where
column1 is not null
and
column1 = 4 OR column1 = 5
在具有真实列名的数据库中,我得到两个不同的结果.带有括号的是正确的,因为如果我这样做:
In my database with the real column names, I get two different results. The one with the parentheses is right because if I do:
select count(*) from my table
where
column1 is not null
and
column1 = 4
然后
select count(*) from my table
where
column1 is not null
and
column1 = 5
并将它们加在一起,我得到正确的答案...我认为.与上面带括号的第一个示例相同.
and add them together, I get the right answer...I think. Same as the first example with the parentheses above.
为什么通过更改OR测试的优先级会得到不同的结果?
Why do I get different results by changing precedence with the OR test?
推荐答案
它不是Oracle或SQL.这是基本的布尔逻辑. AND条件比OR条件更强"(具有优先级),表示将首先对其求值:
It's not Oracle or SQL. It's basic boolean logic. The AND condition is "stronger" (has precedence) than OR, meaning it will be evaluated first:
column1 is not null
and
column1 = 4 OR column1 = 5
手段
column1 is not null
and
column1 = 4
首先评估
,然后在此和column1 = 5
添加括号可确保首先对OR求值,然后对AND求值.
Adding parentheses ensures OR is evaluated first and then the AND.
很像数学:
2 * 3 + 5 = 6 + 5 = 11
但是
2 * (3 + 5) = 2 * 8 = 16
在此处了解更多信息: http://msdn.microsoft.com/en-us/library/ms190276 .aspx
More reading here: http://msdn.microsoft.com/en-us/library/ms190276.aspx
这篇关于在SQL中,使用带有OR的括号是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!