I have a (big) table where I do a query on, using 3 fields in the WHERE
. One of these fields has an index (a date), and I'm looking for hits in the past 3 months. While it'll never be a quick query, the least I hope for is the index on this date to be used.
This is my query:
SELECT id
FROM statsTable
WHERE 1
AND ip = 'ipgoeshere'
AND anotherstring = 'Quite a long string goes here, something like this or even longer'
AND `date` > DATE_ADD( NOW( ) , INTERVAL -3 MONTH )
And it's explain:
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE statsTable ALL date NULL NULL NULL 4833721 Using where; Using filesort
This is a complete table-scan, the number of rows is off because of INNODB-row-counting I guess, but that's all of em. This takes about 30 seconds.
If I force the index like so, I get the expected result:
SELECT id
FROM statsTable FORCE INDEX (date)
WHERE 1
AND ip = 'ipgoeshere'
AND anotherstring = 'Quite a long string goes here, something like this or even longer'
AND `date` > DATE_ADD( NOW( ) , INTERVAL -3 MONTH )
Again, the explain:
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE statsTable range date date 8 NULL 1120172 Using where
Now we have 'only' a million results, but this gets done "lighting" quick (as in, 3 seconds instead of 30).
The table:
CREATE TABLE IF NOT EXISTS `statsTable` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`date` datetime NOT NULL,
`ip` varchar(15) NOT NULL,
`anotherstring` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
KEY `date` (`date`)
) ENGINE=InnoDB;
The strange thing is: I have this table running on another database too (running on a different server), and the index IS being used in that instance. I can't see what could be the issue here. Is there a setting I missed? Or could it be some other minor difference? Apart from the differences, I can't see why above query wouldn't use the key.
I have run OPTIMIZE TABLE
and, as @DhruvPathak suggested ANALYZE TABLE
, but the explain still stays the same. I also tried an ALTER TABLE
as suggested by a friend, to rebuild the index. No luck.