I have a table gamesplatform_pricehistory with an index :
(id_app
,country
,dateup
)
doing this
explain select dateup from gamesplatform_pricehistory
where id_app=1 and country=1
order by dateup desc limit 1
shows "Using where; Using index"
but with a subquery :
explain select app.id, (select dateup from gamesplatform_pricehistory
where id_app=app.id and country=1
order by dateup desc limit 1)
from app where id > 0;
shows Using where; Using index; Using filesort
Here is a sqlfiddle showing directly the problem : http://sqlfiddle.com/#!2/034bc/1
benchmark with millions rows : (table games_platform is the same as app) :
SELECT sql_no_cache thepricehistory.dateup
FROM games_platform
LEFT JOIN (SELECT max(dateup) as dateup, id_app
FROM gamesplatform_pricehistory
WHERE country='229' GROUP BY id_app
) thepricehistory
ON thepricehistory.id_app =games_platform.id
WHERE games_platform.id=2
eval : 0.8s
SELECT sql_no_cache ( SELECT dateup FROM gamesplatform_pricehistory
WHERE id_app= games_platform.id AND country='229'
ORDER BY dateup DESC LIMIT 1
) AS dateup
FROM games_platform
WHERE games_platform.id=2
eval : 0.0003s
See Question&Answers more detail:os