在SQL中,使用带OR的括号表示什么?

问题描述 投票:1回答:3

示例:

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

在具有真实列名的数据库中,我得到两个不同的结果。带括号的是正确的,因为如果我这样做:

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

并将它们加在一起,我得到正确的答案...我认为。与上面带有括号的第一个示例相同。

为什么我通过更改OR测试的优先级得到不同的结果?

sql oracle operator-precedence associativity
3个回答
9
投票

不是Oracle或SQL。这是基本的布尔逻辑。 AND条件比OR“强”(具有优先级),表示将首先对其求值:

column1 is not null
and
column1 = 4 OR column1 = 5

手段

column1 is not null
and
column1 = 4

首先被评估,然后在此和column1 = 5之间应用或”>

添加括号可确保先计算或,然后是与。

非常类似于数学:

2 * 3 + 5 = 6 + 5 = 11

但是

2 * (3 + 5) = 2 * 8 = 16

更多在这里阅读:http://msdn.microsoft.com/en-us/library/ms190276.aspx


3
投票

这取决于您的表达式是否被解析为:


0
投票

无意识状态,(A AND B) OR CA AND (B OR C)就像在数学中一样:(0 * 1) + 20 * (1 + 2)

© www.soinside.com 2019 - 2024. All rights reserved.