在 MySQL 语句中使用 OR 到底有什么不同,带/不带括号?

2021-11-20 00:00:00 sql mysql

我有这个查询:

SELECT * FROM (`users`) WHERE `date_next_payment` <= '2011-02-02' 
    AND `status` = 'active' OR `status` = 'past due'

这不会返回正确的结果.但是,在 OR 条件周围添加括号使其工作如下:

Which does not return the correct results. However, adding parentheses around the OR conditions makes it work like so:

SELECT * FROM (`users`) WHERE `date_next_payment` <= '2011-02-02'
    AND (`status` = 'active' OR `status` = 'past due')

我的问题是为什么不同?我知道这是在不带括号的情况下以不同的方式考虑 OR 语句;但我不明白这有什么不同.

My question is why is it different? I understand that's is considering the OR statement differently without the parentheses; but I don't understand how it's different.

我没有找到任何对此有帮助的文档.如果有任何链接,我将不胜感激.

I haven't found any docs that have been helpful on this. If there's any links out there I'd really appreciate it.

推荐答案

这是因为 OR 具有较低的 运算符优先比 AND .每当数据库看到像

This is because OR has lower operator precedence than AND. Whenever the DB sees an expression like

A AND B OR C

先评估AND,即它等价于

the AND is evaluated first, i.e. it is equivalent to

(A AND B) OR C

所以如果你明确想要

A AND (B OR C)

相反,您必须放入括号.

instead, you must put in the parentheses.

顺便说一下,这不是 SQL 特有的.这些运算符的优先顺序在我知道的所有编程语言中都是相同的(即至少是 C、C++、C#、Java 和 Unix shell 脚本).

This is btw not specific to SQL. The order of precedence of these operators is the same in all programming languages I know (i.e. at least C, C++, C#, Java and Unix shell scripts).

相关文章