Sidney
Sidney

Reputation: 708

mysql "or" order of query operations

So I'm working with laravel 3 which use eloquent ORM on a mysql database. I've got a function that makes repeated round trips to the SQL server, and I've got it working with my limited test cases, but I'm not 100% sure about the order of operations in an sql query, so I was hoping someone could give me an idea of if I am correct. The old code is as follows

    $notifications = Notification::where(condition-1-a)->where(condition-1-b)->get();
    foreach ($locations = DB::table(table)->where(propertyX)->get() as $location) {
        $extra_notifications = Notification::where(condition-2-a)->where(condition-2-b)->get();
        $notifications = array_merge($notifications,$extra_notifications);
    }

I know the above code works, and keeps things isolated, because each query is run as it's own entity, and then the results are merged, but once you start getting more locations it takes a looong time to run. I'm trying to reduce this by having only one trip to the sql server, and have come up with this code.

    $notifications = Notification::where(condition-1-a)->where(condition-1-b);
    foreach ($locations = DB::table(table)->where(propertyX)->get() as $location) {
        $notifications = $notifications -> or_where(condition-2-a)->where(condition-2-b);
    }
$notifications = $notifications->get();

My problem here is that I'm not sure how or_where works. It generates an sql string with words I'm familiar with as a code, but I'm not sure they will work the same way. The generated string is

SELECT * FROM `notifications` 
    WHERE `condition-1-a` = ? AND `condition-1-b` = ? 
    OR `condition-2-a` = ? AND `condition-2-b` = ? 
    OR `condition-2-a` = ? AND `condition-2-b` = ? 
    OR `condition-2-a` = ? AND `condition-2-b` = ? 
    ... (etc depending on number of loop iterations)

The main thing I'm looking for is confirmation of how the query runs. Can I expect to run like this?

SELECT * FROM `notifications` 
    WHERE (`condition-1-a` = ? AND `condition-1-b` = ?) 
    OR (`condition-2-a` = ? AND `condition-2-b` = ? )
    OR (`condition-2-a` = ? AND `condition-2-b` = ? )
    OR (`condition-2-a` = ? AND `condition-2-b` = ? )
    ... [etc depending on number of loop iterations]

Or is there some other order in which sql statments are evaluated?

(I redacted some variable names and other aspects of the code, I did my best to boil it down to something everyone can use so that it's not specific to my situation)

Upvotes: 0

Views: 114

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191779

MySQL operator precedence

AND has higher precedence than OR. Your first example is the same as your second.

Upvotes: 2

Related Questions