How exactly does using OR in a MySQL statement differ with/without parentheses?

后端 未结 8 1597
难免孤独
难免孤独 2020-11-29 08:20

I have this query:

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


        
8条回答
  •  醉梦人生
    2020-11-29 09:19

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

    A AND B OR C
    

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

    (A AND B) OR C
    

    So if you explicitly want

    A AND (B OR C)
    

    instead, you must put in the parentheses.

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

提交回复
热议问题