MySQL AND/OR grouping

In the process of switching my sites output from static pages generated by MovableType to dynamic pages using PHP I've written myself one of the steps was to change de feeds. These are now parsed by php.

Yesterday I discovered a bug in the main feeds. These feeds contain both blog and photography posts. The funny thing was that photography drafts were shown in the feed as to blog drafts were kept secret.

<!--more-->

To me this seemed like a problem with the query that fetches the posts:

mysql_query("
SELECT entry_created_on
FROM mt_entry
WHERE entry_blog_id = '7' OR entry_blog_id = '4' AND entry_status = '2'
ORDER BY entry_created_on
DESC LIMIT 1
")

The only thing I could think of was changing the WHERE line, resulting in the following code.

mysql_query("
SELECT entry_created_on
FROM mt_entry
WHERE entry_blog_id = '7' AND entry_status = '2' OR entry_blog_id = '4' AND entry_status = '2'
ORDER BY entry_created_on
DESC LIMIT 1
")

Funny enough this solved the problem. Apparently MySQL group the arguments before and after the OR. I always thought it would first check where entries had one of the two blog id's and would then check the entry status. Something like this:

WHERE
[entry_blog_id = '7' OR entry_blog_id = '4']
AND
entry_status = '2'

Instead MySQL checks the argument before OR and then after.

WHERE
[entry_blog_id = '7']
OR
[entry_blog_id = '4' AND entry_status = '2']

Is there a way I can tell MySQL to use the first interpretation instead of having to add the entry_status twice?

23 juni 2004

English, php, Programmeren, Web

back to top