在带/不带括号的MySQL语句中使用OR到底有何不同? [英] How exactly does using OR in a MySQL statement differ with/without parentheses?

查看:386
本文介绍了在带/不带括号的MySQL语句中使用OR到底有何不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个查询:

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的

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).

这篇关于在带/不带括号的MySQL语句中使用OR到底有何不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆