The query below takes about 0.3 seconds. Why? And how can I solve it. The shouldnt take so long…
SELECT tshops.OfficialName
, tresults.StartTime
, tresults.Price
, tresults.shopID
FROM
tresults
INNER JOIN tshops
ON tshops.shopID = tresults.shopID
WHERE
tresults.pID = 15
AND tresults.websiteID = 1
AND tresults.StartTime = (SELECT max(tresults.StartTime) AS maxstarttime
FROM
tresults
WHERE
tshops.shopID = tresults.shopID
AND tresults.pID = 15
AND tresults.websiteID = 1)
ORDER BY
tresults.Price DESC
Explain result:
1, PRIMARY, tshops, ALL, PRIMARY, , , , 203, Using temporary; Using filesort
1, PRIMARY, tresults, eq_ref, PRIMARY,idxPID,idxWebsite,idxStartTimeASC,idxStartTimeDESC,fk_shopID, PRIMARY, 20, func,const,pricegrabber.tshops.shopID,const, 1, Using where
2, DEPENDENT SUBQUERY, tresults, ref, idxPID,idxWebsite,fk_shopID, fk_shopID, 4, pricegrabber.tshops.shopID, 891, Using where; Using index
So a full table scan on tshops is done. But why? There’s an index on shopID in both tables…
I would suspect the subselect which refers to the outer select is confusing matters.
Try doing a join against the subselect, using a GROUP BY on the shopID. Normally I would expect MySQL to optimise things to do this anyway, but worth a try.
Something like this (please excuse any typos)