I've checked numerous other SO posts and MySQL docs but can't seem to get an answer on why an index isn't being used, and how to force it to be used - I can see many others are having similar problems, but can't find a solution.
The table looks like this
CREATE TABLE `countries_ip` (
`ipfrom` INT(10) UNSIGNED ZEROFILL NOT NULL,
`ipto` INT(10) UNSIGNED ZEROFILL NOT NULL,
`countrySHORT` CHAR(2) NULL DEFAULT NULL,
`country_id` INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (`ipfrom`, `ipto`, `country_id`),
INDEX `from_to_index` (`ipfrom`, `ipto`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;
Not sure why the "from_to_index" is there - seems redundant to me. But anyway, the EXPLAIN query looks like this
EXPLAIN SELECT *
FROM track_report t, countries_ip ip
WHERE t.ip BETWEEN ip.ipfrom AND ip.ipto
and the result of the EXPLAIN is as follows:
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE t ALL getwebmaster NULL NULL NULL 36291
1 SIMPLE ip ALL PRIMARY,from_to_index NULL NULL NULL 153914 Range checked for each record (index map: 0x3)
As you can see, the PRIMARY KEY from the countries_ip
table isn't being used and so the query takes a LONG time (countries_ip
has over 150k records)
I'm probably missing something simple, but any advice would be appreciated on how I can optimize this query. Thanks in advance.