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

后端 未结 8 1613
难免孤独
难免孤独 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 08:58

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

    In this example, you will get all records where either

    a) The date_next_payment is before 2nd Feb 2011 AND status is active

    b) The status is past_due

    So the past_due records will not be restricted by date.

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

    In this example, you will get all records where

    a) The date_next_payment is before 2nd Feb 2011

    AND

    b) The status is either active or past_due

    The brackets work like they do in maths or logic - the statements inside the brackets get evaluated first... so imagine seeing each step take place like this:

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

    So a record is encountered with a status of active...

    SELECT * FROM (`users`) WHERE `date_next_payment` <= '2011-02-02'
    AND (TRUE OR FALSE)
    

    This then evaluates, with the OR condition... (TRUE OR FALSE) == TRUE

    SELECT * FROM (`users`) WHERE `date_next_payment` <= '2011-02-02'
    AND TRUE
    

    And the date is 2011-01-01

    SELECT * FROM (`users`) WHERE TRUE
    AND TRUE
    

    And finally, TRUE AND TRUE == TRUE

    SELECT * FROM (`users`) WHERE TRUE
    

    And so the record is returned...

    Imagining your query being executed in steps like this against each row in the database sometimes helps to understand where to put your brackets.

提交回复
热议问题