I often read articles saying to combine statements and send less queries. But you seldom see advise about splitting queries to improve performance. Here is what I came across just the other day:
SELECT IF(`uid_to`=@user, `uid_from`, `uid_to`) AS `uid`, `message`, `date`, `uid_to`=@user AS received FROM `beepme_msg` WHERE (`uid_from`=@user AND `uid_to`!=@user) OR (`uid_to`=@user AND `uid_from`!=@user) ORDER BY `uid_to`, `date`;
The query gets all messages send and received by the user, filtering our message the user send to himself. This looks like a good query since you’ll get all you data in one call. In reality it will mess up your performance, since it can’t use any indexes and will therefor use a table scan. And as we know, tables scans are slow.
The ‘OR’ statement basically messes this up, since only one index can be used per table. We can see what happens a bit better if …
[Read more]