oracle 在 SQL 中,将括号与 OR 一起使用是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10034489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In SQL, what does using parentheses with an OR mean?
提问by johnny
Example:
例子:
select count(*) from my table
where
column1 is not null
and
(column1 = 4 OR column1 = 5)
Example 2:
示例 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
and then
进而
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.
并将它们加在一起,我得到了正确的答案......我想。与上面括号中的第一个示例相同。
Why do I get different results by changing precedence with the OR test?
为什么通过更改 OR 测试的优先级会得到不同的结果?
回答by CyberDude
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:
它不是 Oracle 或 SQL。这是基本的布尔逻辑。AND 条件比 OR 条件“强”(有优先权),这意味着它将首先被评估:
column1 is not null
and
column1 = 4 OR column1 = 5
Means
方法
column1 is not null
and
column1 = 4
is evaluated first, then OR is applied between this and column1 = 5
首先评估,然后在此和之间应用 OR column1 = 5
Adding parentheses ensures OR is evaluated first and then the AND.
添加括号可确保先计算 OR,然后再计算 AND。
Pretty much like in maths:
很像数学:
2 * 3 + 5 = 6 + 5 = 11
but
但
2 * (3 + 5) = 2 * 8 = 16
More reading here: http://msdn.microsoft.com/en-us/library/ms190276.aspx
回答by Matt Fenwick
This comes down to whether your expression is parsed as:
这归结为您的表达式是否被解析为:
(column1 is not null and column1 = 4) OR column1 = 5
or
或者
column1 is not null and (column1 = 4 OR column1 = 5)
See the difference?
看到不同?
回答by Maxime 1000he
Parenthesis matter, (A AND B) OR C
≠ A AND (B OR C)
just like in math: (0 * 1) + 2
≠ 0 * (1 + 2)
括号很重要,(A AND B) OR C
≠ A AND (B OR C)
就像在数学中一样:(0 * 1) + 2
≠ 0 * (1 + 2)
However, you can choose not to use parenthesis : SQL doesn't have operator precedence rules, so it strictly evaluates expressions from left to right. For instance:
但是,您可以选择不使用括号:SQL 没有运算符优先级规则,因此它严格从左到右计算表达式。例如:
true OR false AND false
is false, just like
是假的,就像
(true OR false) AND false
while
尽管
true OR (false AND false)
is true.
是真的。