Friday, 13 September 2013

why is select much slower with left join+where

why is select much slower with left join+where

I am attempting to optimize a MySQL query that is taking a long time to
process. Imagine we have two tables, a users table and a purchases table.
Both tables have ~20,000 rows in them.
mysql> select NOW(),u.id from users u left join purchases p on p.user_id =
u.id where p.website_id = 1234 order by u.total_paid desc limit 10;
+---------------------+-------+
| NOW() | id |
+---------------------+-------+
*snip*
+---------------------+-------+
10 rows in set (0.06 sec)
Not super fast but pretty snappy. If I change nothing other than change
u.id to u.* it will slow down dramatically:
mysql> select NOW(),u.* from users u left join purchases p on p.user_id =
u.id where p.website_id = 1234 order by u.total_paid desc limit 10;
+---------------------+-------+
*snip*
+---------------------+-------+
10 rows in set (0.37 sec)
Before you say "Well, you should never use select *" consider that it
slowly creeps up to that length of time the more fields you add, i.e.
naming half of the fields to select will cause the query execute in ~0.20
seconds and no field on the users table is larger than a varchar(255).
However, if I take the ids from my relatively snappy query and I simply:
mysql> select * from users where id in (*snip*);
+---------------------+-------+
*snip*
+---------------------+-------+
10 rows in set (0.01 sec)
So my two queries: select u.id plus select u.* where id in is faster than
what I assume is a similar query. What the heck?

No comments:

Post a Comment