【问题标题】:Mysql not using index when a length is different长度不同时Mysql不使用索引
【发布时间】:2014-12-10 13:44:19
【问题描述】:

最近在 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 位数字,即 3159544575 表示 188.82.206.157 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

感谢您的帮助

【问题讨论】:

  • explain select ... 输出是什么?
  • 首先正如 juergen d 所说,我们需要选择的解释。 secone 您是否尝试过以不同的方式编写查询?
  • 尝试使用 INET_ATON 并手动转换 IP。我也更新了这个问题。谢谢

标签: mysql indexing


【解决方案1】:

感谢

Optimizing MySQL query for integer range search

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-15
    • 1970-01-01
    • 2018-02-22
    • 2011-07-22
    • 1970-01-01
    • 2019-12-19
    • 2018-08-02
    • 1970-01-01
    相关资源
    最近更新 更多