I have stored temperatures in a MySQL database. The table is called temperatures. It contains, for example, the columns dtime and temperature. The first one is the time the temperature was measured (the column type is DATETIME) and the latter, well, apparently the temperature (the type is FLOAT).
At the moment I use the following query to fetch the temperatures in a certain period.
SELECT dtime, temperature
FROM temperatures
WHERE dtime BETWEEN "2012-11-15 00:00:00" AND "2012-11-30 23:59:59"
ORDER BY dtime DESC
I’d like to add the average temperature of the day in the results. I tried the following.
SELECT
dtime AS cPVM,
temperature,
(
SELECT AVG(temperature)
FROM temperatures
WHERE DATE(dtime) = DATE(cPVM)
) AS avg
FROM temperatures
WHERE dtime BETWEEN "2012-11-15 00:00:00" AND "2012-11-30 23:59:59"
ORDER BY dtime DESC
Works ok, but this is really, really slow. Fetching the results in that period takes about 5 seconds, when the first one (without the averages) is done in 0.03 seconds.
SELECT DATE(dtime), AVG(temperature)
FROM temperatures
WHERE DATE(dtime) BETWEEN "2012-11-15" AND "2012-11-30"
GROUP BY DATE(dtime)
ORDER BY dtime DESC
This one however is done in 0.04 seconds.
How do I fetch the average temperatures more efficiently?
Use a join instead of a correlated subquery: