我试图解决一个问题,可以比较两列在一个表。表如下
------------------------------------------
| from | to | Country |
------------------------------------------
| 25.0.0.1 | 25.255.255.255 | denmark |
------------------------------------------
| 68.0.0.1 | 68.255.255.255 | USA |
我的问题是,我有一个25.195.32.0
的ip,我想将它与from
和to
列进行比较,并返回country name
。
发布于 2014-05-05 06:47:46
您可以使用INET_ATON
获取要比较的IP的数值。
SELECT country FROM table
WHERE INET_ATON('25.195.32.0') BETWEEN INET_ATON(from) AND INET_ATON(to)
inet-aton
发布于 2014-05-05 06:48:40
您可以通过使用IN()
或OR
找到使用AND
尝试条件
WHERE from IN('your_ip') OR to IN('your_ip')
发布于 2014-05-05 06:50:11
将IP转换为整数,然后比较整数是简单的。MySQL提供了这样做的inet_aton
函数。
select Country from table_name where inet_aton($ip) between inet_aton(`from`) and inet_aton(`ip`);
为了提高性能,应该将列from
、to
转换为整数。例如:添加到列from_n
,to_n
。然后您的SQL将如下所示:
select Country from table_name where inet_aton($ip) between `from_n` and `to_n`
如果不使用MySQL,则应该首先将$ip
转换为整数$ip_n (使用类似于Python的socket.inet_aton
),然后将inet_aton($ip)
替换为$ip_n
。
https://stackoverflow.com/questions/23466291
复制相似问题