tags:

views:

27

answers:

1

I have the following query that is being logged as a slow query:

EXPLAIN EXTENDED SELECT *
FROM (
`photo_data`
)
LEFT JOIN `deleted_photos` ON `deleted_photos`.`photo_id` = `photo_data`.`photo_id`
WHERE `deleted_photos`.`photo_id` IS NULL
ORDER BY `upload_date` DESC
LIMIT 50 

Here's the output of explain:

id  select_type  table  type  possible_keys  key  key_len  ref  rows  Extra
1  SIMPLE  photo_data  index  NULL  upload_date  8  NULL  142523   
1  SIMPLE  deleted_photos  eq_ref  photo_id  photo_id  767  tbc.photo_data.photo_id  1  Using where; Not exists

I can see that it's having to go through all 142K records to pull the latest 50 out of the database.

I have these two indexes:

UNIQUE KEY `photo_id` (`photo_id`),
KEY `upload_date` (`upload_date`)

I was hoping hat the index key on upload_date would help limit the number rows. Anythoughts on what I can do to speed this up?

+2  A: 

You could add a field to your photo_data table which shows whether or not it is deleted instead of having to find out this fact by joining to another table. Then if you add an index on (deleted, upload_date) your query should be very fast.

Mark Byers
Ok I will give that a go thanks
Mark Steudel
So I profiled the queries the new one: SELECT `photo_data`.`photo_id`, `photo_data`.`image_fullsize`, `image_thumbnail`, `photo_description`FROM (`photo_data`)WHERE `deleted` = '0'ORDER BY `upload_date` descLIMIT 50This new spends 1.2 seconds sorting .... I added a new index on deleted ...
Mark Steudel
@Mark Steudel: Have you tried adding a combined index on `(deleted, upload_date)` as I suggested in my post? I can't remember the exact syntax for creating indexes, but something along these lines: `ALTER TABLE photo_data ADD INDEX deleted_upload_date (deleted, upload_date)`. I think that this will make a huge difference to the speed of the query as it should go from O(n log n) to almost O(1).
Mark Byers