咨询老师一个关于ip匹配的索引问题:
有一个IP的库表,每一条记录了一个开始ip和结束ip,然后想批量匹配ip,查询为何没有用上“联合索引KEY `ip_range_int` (`start_int`,`end_int`) USING BTREE”?要怎么设置索引才有效?
CREATE TABLE `t_dt_ip` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`start_ip` char(15) DEFAULT NULL,
`end_ip` char(15) DEFAULT NULL,
`location` varchar(100) DEFAULT NULL,
`start_int` int(10) unsigned DEFAULT '0',
`end_int` int(10) unsigned DEFAULT '0',
PRIMARY KEY (`id`),
KEY `ip_range` (`start_ip`,`end_ip`) USING BTREE,
KEY `ip_range_int` (`start_int`,`end_int`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
explain update t_tmp_ip t, t_dt_ip i
set t.ip_id = i.id
where INET_ATON(t.ip_address) between i.start_int and i.end_int;
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
| 1 | UPDATE | t | NULL | ALL | NULL | NULL | NULL | NULL | 1000 | 100.00 | NULL |
| 1 | SIMPLE | i | NULL | ALL | ip_range_int | NULL | NULL | NULL | 541942 | 11.11 | Range checked for each record (index map: 0xC) |
甚至加上单个字段索引也没有用??
alter table `t_dt_ip` add index indx_t_dt_ip_start_int (start_int);
mysql> explain select * from t_dt_ip i join t_tmp_ip t on 1= 1 where t.ip_address >= i.start_int limit 1;
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
| 1 | SIMPLE | t | NULL | ALL | NULL | NULL | NULL | NULL | 73126 | 100.00 | NULL |
| 1 | SIMPLE | i | NULL | ALL | ip_range_int,indx_t_dt_ip_start_int | NULL | NULL | NULL | 541942 | 33.33 | Range checked for each record (index map: 0xC) |
展开