Mysql优先级逻辑
对以下查询的任何解释:
Select x FROM y WHERE a = 1 OR a = 2 AND (b = 1 OR b = 2)
为什么它不返回正确的信息,而这返回正确的信息:
Select x FROM y WHERE (a = 1 OR a = 2) AND (b = 1 OR b = 2)
我在这里遗漏了什么吗?
X Y (X OR Y) X OR Y
1 0 1 1
0 1 1 1
1 1 1 1
0 0 0 0
我知道就优先级而言 () 具有优先级,但为什么我应该将它们添加到查询的第一部分?
如果我错了请纠正我
谢谢
Any explanation to the following queries :
Select x FROM y WHERE a = 1 OR a = 2 AND (b = 1 OR b = 2)
why it doesn't return the correct info while this return the correct info :
Select x FROM y WHERE (a = 1 OR a = 2) AND (b = 1 OR b = 2)
Am i missing something here ?
X Y (X OR Y) X OR Y
1 0 1 1
0 1 1 1
1 1 1 1
0 0 0 0
I know in term of precedence the () have priority , but why should i add them the the first part of the query ?
Correct me if I'm wrong
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
AND
的优先级高于OR
,因此您的第一个查询相当于:这不等于
我猜您忘记了
a = 3
参与您的第一个查询。MySQL 中的运算符优先级
AND
has a higher precedence thanOR
so your first query is equivalent to this:Which is not equivalent to
I guess you forgot the
a = 3
part in your first query.Operator precedence in MySQL
因为含糊不清是一种不受欢迎的特质?
此外,如果优化器认为 WHERE 条件的性能会更好,则会重新排序。因此,您的歧义将导致不同的结果,具体取决于它首先评估的方式/内容。
始终明确您的意图。
Because ambiguity is an undesirable trait?
Also, the optimizer will re-order your WHERE Conditions if it thinks it will perform better. Your ambiguity will, therefore, cause different results depending on how/what it evaluates first.
Always be explicit with your intentions.
在 WHERE 子句中使用括号不仅会影响优先级,还会将谓词分组在一起。在您的示例中,结果的差异更多的是分组问题而不是优先级问题。
您可以将其视为: (pN = 谓词表达式)
as:
以及 this:
as: ,
因此很明显,结果可能完全不同。
Using parentheses in your WHERE clause does not just affect precedence but also groups predicates together. In your example the difference in results is more a matter of grouping rather than precedence.
You could think of this: (pN = predicate expression)
as:
And this:
as:
and so it becomes clear that the results could be quite different.