Mysql优先级逻辑

发布于 2024-11-30 14:37:45 字数 495 浏览 2 评论 0原文

对以下查询的任何解释:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

很快妥协 2024-12-07 14:37:45

AND 的优先级高于 OR,因此您的第一个查询相当于:

Select x FROM y WHERE a = 1 OR a = 3 OR (a = 2  AND (b = 1 OR b = 2))

这不等于

Select x FROM y WHERE (a = 1 OR a = 2 OR a = 3) AND (b = 1 OR b = 2)

我猜您忘记了 a = 3参与您的第一个查询。

MySQL 中的运算符优先级

AND has a higher precedence than OR so your first query is equivalent to this:

Select x FROM y WHERE a = 1 OR a = 3 OR (a = 2  AND (b = 1 OR b = 2))

Which is not equivalent to

Select x FROM y WHERE (a = 1 OR a = 2 OR a = 3) AND (b = 1 OR b = 2)

I guess you forgot the a = 3 part in your first query.

Operator precedence in MySQL

久随 2024-12-07 14:37:45

因为含糊不清是一种不受欢迎的特质?

此外,如果优化器认为 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.

友谊不毕业 2024-12-07 14:37:45

在 WHERE 子句中使用括号不仅会影响优先级,还会将谓词分组在一起。在您的示例中,结果的差异更多的是分组问题而不是优先级问题。

您可以将其视为: (pN = 谓词表达式)

WHERE a = 1 OR a = 2  AND (b = 1 OR b = 2)

as:

WHERE p1 OR p2 AND p3

以及 this:

WHERE (a = 1 OR a = 2 OR a = 3) AND (b = 1 OR b = 2)

as: ,

WHERE p1 AND p2

因此很明显,结果可能完全不同。

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)

WHERE a = 1 OR a = 2  AND (b = 1 OR b = 2)

as:

WHERE p1 OR p2 AND p3

And this:

WHERE (a = 1 OR a = 2 OR a = 3) AND (b = 1 OR b = 2)

as:

WHERE p1 AND p2

and so it becomes clear that the results could be quite different.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文