当长度不同时,Mysql不使用索引

时间:2014-12-10 13:44:19

标签: mysql indexing

最近发现了MYSQL这个有趣的问题。花了几个小时在网上阅读,仍然无法提出解决方案。

大表描述如下:

CREATE TABLE `ip_country_region_city` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ip_from` int(11) unsigned NOT NULL,
`ip_to` int(11) unsigned NOT NULL,
 .........
 PRIMARY KEY (`id`),
 KEY `ipindex` (`ip_from`,`ip_to`)
) ENGINE=InnoDB AUTO_INCREMENT=16908031 DEFAULT CHARSET=utf8;

此表用于ip-range搜索。

以下查询用于示例/测试查询:

SELECT * FROM ip_country_region_city
WHERE   455141527   BETWEEN ip_from AND ip_to

其中455141527是给定的IP地址,表示为27.32.232.151的数字

然后,MYSQL将使用" ipindex"对于上述IP地址。 但是,我们是否应该为此查询提供一个不同的IP地址,该地址代表一个10位数字,即对于188.82.206.157的3159544575,mysql不会使用' ipindex'一点都不。

EXPLAIN SELECT * FROM ip_country_region_city
WHERE  INET_ATON("27.32.232.151")    BETWEEN ip_from AND ip_to

使用上述索引

返回
1   SIMPLE  ip_country_region_city  range   ipindex ipindex 4       746392  Using where

EXPLAIN SELECT * FROM ip_country_region_city
WHERE  INET_ATON("188.82.206.157")    BETWEEN ip_from AND ip_to

返回NULL作为索引使用

1   SIMPLE  ip_country_region_city  ALL ipindex             6716010 Using where

感谢您的协助

1 个答案:

答案 0 :(得分:0)

感谢

Optimizing MySQL query for integer range search

我能够重建此查询并使其正常工作,