I'm using mysql 5.5
Here is my table:
CREATE TABLE `temperature_information`
(
`id` int(11) NOT NULL AUTO_INCREMENT,
`device` int(11) NOT NULL,
`temperature` int(11) NOT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `device` (`device`),
KEY `date` (`date`),
KEY `idx` (`device`, `date`)
) ENGINE=InnoDB AUTO_INCREMENT=25602738 DEFAULT CHARSET=latin1
This table has ~50m. records.
Here is my query:
SELECT
date AS ValueDate, MAX(temperature)
FROM
(SELECT
date, temperature
FROM
temperature_information
WHERE
device = 1111
ORDER BY
temperature DESC) c
GROUP BY
DATE(ValueDate), HOUR(ValueDate)
This query returns Maximum temperature for each day. It's execution time is ~0.9 s. and subquery's time 0.003 sec.
I have index on date, device columns and multicolumn index idx on date and device. Explain says it uses device index for query, which is good (subquery is very fast). But to get Max temperature for each day I need to use Group BY. I know that fuctions on indexed column disables use of index, but I don't know workaround how to make it efficient and produce same results.
My question: is it possible to write query which would be more efficient and would produce same results or I should process rows returned by sub query and find Max temperature for each day myself (this would be written in c)?
Sub query returns 20-40k rows on average.