I have a table like this, it has millions of records:
CREATE TABLE `myTable` (
`DateTime` DATETIME NOT NULL,
`Col1` MEDIUMINT UNSIGNED NOT NULL,
`Col2` MEDIUMINT UNSIGNED NOT NULL,
`Col3` MEDIUMINT UNSIGNED NOT NULL,
`Col4` MEDIUMINT UNSIGNED NOT NULL,
`Event` MEDIUMINT UNSIGNED NOT NULL,
`State` MEDIUMINT UNSIGNED NOT NULL,
PRIMARY KEY (`DateTime`,`Col4`,`Event`,`State`)
);
I run a query to count the number of records, grouped by a time period, for a time range, if they match 'filters' based on the Col1/Col2/Col3/Col4 values. For example, a 3 minute period:
select
FROM_UNIXTIME(UNIX_TIMESTAMP(MIN(`DateTime`))-(UNIX_TIMESTAMP(MIN(`DateTime`)) % (3*60))) as 'Period',
count(*) as 'NumberOfRecords'
from
`myTable`
where
`DateTime` > '2016-09-01' and `DateTime` < '2016-09-09'
AND `Col1` IN (3, 6, 11, 14, etc... )
AND `Col2` IN (5 ,25 , 325 , 293, 294, etc.... )
AND `Col3` IN (3 , 9 , 95 , 395 , 435, etc...)
AND `Col4` IN (124, 125, 135, 325, etc...)
group by
UNIX_TIMESTAMP(`DateTime`) DIV (3*60);
What index should I have to speed up this query? I don't care how slow insertion gets, I want to have the query run extremely fast.
In general there are around 1,000 unique values for each col1,col2,col3,col4, but there are millions of records that would fit in the date range.
I was thinking something like:
CREATE INDEX `myIndex` ON `myTable` ( `DateTime`, `Col`,`Col2`,`Col3`,`Col4 )
But I am not sure I have the ordering right? Or is it better to make 4 indexes, one for each (DateTime,ColX)?
DateTime,Col1,col2,col4)?