Win*_*ges 4 mysql ip group-by subnet
我需要按子网(前3个八位字节)对IP列表进行分组来计算它.例如,如果我有Ips
123.12.12.12
123.12.12.11
123.12.11.11
Run Code Online (Sandbox Code Playgroud)
我必须得到这样的结果:
123.12.12 | 2
123.12.11 | 1
Run Code Online (Sandbox Code Playgroud)
我用谷歌搜索了这个例子:
select
substr(ip,1,locate('.',ip,locate('.',ip)+1)-1)
as ip, count(ip) as count
from ip_list
group by ip ORDER BY count DESC
Run Code Online (Sandbox Code Playgroud)
但它只按前两个八位字节对列表进行分组.我迷失在所有这些中locate(locate(locate(...))).有人可以帮助修改它以获得正确的结果吗?
您应该使用group by 表达式名称.
select
-- locate( '.', ip, locate( '.', ip, locate( '.', ip ) + 1 ) + 1 ) as l,
substr( ip, 1, locate( '.', ip
, locate( '.', ip
, locate( '.', ip ) + 1 ) + 1 ) - 1 ) as subip,
count(ip) as count
from ip_list
group by ( subip )
order by count desc
;
Run Code Online (Sandbox Code Playgroud)
编辑1:
使用locate是不需要的.SUBSTR_INDEX可用于过滤IP的子集.
示例:
select
substring_index( ip, '.', 3 ) as subip
, count(ip) as count
from ip_list
group by ( subip )
order by count desc
Run Code Online (Sandbox Code Playgroud)
请参阅文档: