[英]Why is MySQL not using composite key in range query?
我检查了许多其他的SO帖子和MySQL文档,但似乎无法获得为何不使用索引以及如何强制使用索引的答案-我可以看到许多其他问题也有类似的问题,但是找不到解决方案。
桌子看起来像这样
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;
不知道为什么“ from_to_index”在那里-对我来说似乎多余。 但是无论如何,EXPLAIN查询看起来像这样
EXPLAIN SELECT *
FROM track_report t, countries_ip ip
WHERE t.ip BETWEEN ip.ipfrom AND ip.ipto
并且EXPLAIN的结果如下:
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)
正如你所看到的,从该PRIMARY KEY countries_ip
不使用表等的查询需要较长的时间( countries_ip
拥有超过15万条记录)
我可能缺少一些简单的东西,但是任何有关如何优化此查询的建议将不胜感激。 提前致谢。
在track_report.ip
上定义索引可能会有所帮助。 请参见SQL Fiddle 。
我修改了where子句以进行显式比较,现在它使用from_to_index。
SELECT ip
FROM track_report t, countries_ip ip
where t.ip >= ip.ipfrom and t.ip <= ip.ipto
请参见SQL Fiddle 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.