2012-04-18 113 views
0

我发现this question关于通过模式对MySQL搜索进行分组,但我需要为IP地址执行此操作。我需要将前3个八位字节的IP地址分组,但我不太明白如何实现这一点。REGEX寻找IP地址的MySQL搜索

感谢

+0

你能提供一个你想要达到的输出的例子吗?你只想要一个独特的前3个八位字节的列表,或者你是在追寻别的东西吗? – Tim 2012-04-18 16:00:07

+0

@Tim - 是的,所有IP地址的前3个八位字节的列表以及每个IP地址的计数。 – 2012-04-18 16:04:47

回答

2

MySQL SUBSTRING_INDEX function可能会在这里有用:

drop table if exists test_ip; 

create table test_ip 
(id int unsigned not null primary key auto_increment, 
ip varchar(50) not null, 
UNIQUE KEY test_ip_uidx1 (ip)); 

insert into test_ip (ip) values ('24.21.114.4'); 
insert into test_ip (ip) values ('24.21.114.5'); 
insert into test_ip (ip) values ('24.21.114.6'); 
insert into test_ip (ip) values ('24.21.115.6'); 
insert into test_ip (ip) values ('24.21.115.7'); 
insert into test_ip (ip) values ('24.21.115.8'); 
insert into test_ip (ip) values ('24.21.116.1'); 

select substring_index(ti.ip,'.',3) as firstThreeOctet,count(*) as ipCount 
from test_ip ti 
group by substring_index(ti.ip,'.',3); 

希望它能帮助。

+0

甜!你是这个MySQL n00b的男人之神! – 2012-04-18 16:22:38