MySQL LEFT JOIN with ORDER BY – Improve Query Performance

join;MySQL

I have three tables in MySQL – gallery, gallery_likes and gallery_info.

I want to obtain photos from gallery based on the folowing query:

SELECT g.photo_id, g.name
FROM gallery g 
LEFT JOIN gallery_likes AS gl ON gl.info_id = g.info_id
LEFT JOIN gallery_info AS gi ON gi.id = g.info_id
WHERE gl.user_id = 456 AND gl.photo_id < 113535 
ORDER BY gi.insert_date DESC 
LIMIT 10

However, ORDER BY in this setup is very slow. Query takes 5s. If I use ORDER BY g.info_id instead, it takes 200ms.

I have index on id, info_id, photo_id and insert_date columns

Best Answer

You need the next indexes:

gallery:       info_id
gallery_likes: (info_id, user_id, photo_id)
gallery_info:  (id, insert_date)