我在一个表中有超过 170 万条记录,其中包含主键和相应详细信息的 IP 地址范围(开始和结束)。
表结构是
mysql> desc csv;
+---------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| begin | bigint(20) | NO | PRI | 0 | |
| end | bigint(20) | NO | PRI | 0 | |
| code | char(2) | YES | | NULL | |
| country | varchar(50) | YES | | NULL | |
| city | varchar(50) | YES | | NULL | |
| area | varchar(50) | YES | | NULL | |
+---------+-------------+------+-----+---------+-------+
由于主键中的索引,当要像这样进行完全匹配时,搜索速度很快
mysql> SELECT * FROM csv WHERE begin=3338456576;
+------------+------------+------+---------------+----------+---------------+
| begin | end | code | country | city | area |
+------------+------------+------+---------------+----------+---------------+
| 3338456576 | 3338456831 | US | UNITED STATES | NEW YORK | NEW YORK CITY |
+------------+------------+------+---------------+----------+---------------+
1 row in set (0.03 sec)
但是当我尝试在一个范围内搜索时,它需要更长的时间。
mysql> SELECT * FROM csv WHERE begin<3338456592 AND end>3338456592;
+------------+------------+------+---------------+----------+---------------+
| begin | end | code | country | city | area |
+------------+------------+------+---------------+----------+---------------+
| 3338456576 | 3338456831 | US | UNITED STATES | NEW YORK | NEW YORK CITY |
+------------+------------+------+---------------+----------+---------------+
1 row in set (1.59 sec)
有什么方法可以优化我的查询以在一个范围内搜索 IP 地址?
编辑
创建表语句
CREATE TABLE `csv` (
`begin` bigint(20) NOT NULL DEFAULT '0',
`end` bigint(20) NOT NULL DEFAULT '0',
`code` char(2) DEFAULT NULL,
`country` varchar(50) DEFAULT NULL,
`city` varchar(50) DEFAULT NULL,
`area` varchar(50) DEFAULT NULL,
PRIMARY KEY (`begin`,`end`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;