我有一个MySQL表设置如下:
+---------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------+-------------+------+-----+---------+----------------+
| ipaddress_s | varchar(15) | YES | MUL | NULL | |
| ipaddress_e | varchar(16) | YES | | NULL | |
+---------------+-------------+------+-----+---------+----------------+
其中,ipaddress_s和ipaddress_e类似于:4.100.159.0-4.100.159.255
现在有没有办法让我真正得到包含给定IP地址的行?例如,给定IP地址:“4.100.159.5”,我希望返回上面的行。所以我正在尝试看起来像这样的查询(但当然这是错误的,因为在下面我将IP视为字符串):
SELECT * FROM ranges WHERE ipaddress_s<"4.100.159.5" AND ipaddress_e>"4.100.159.5"
有什么建议吗?
答案 0 :(得分:8)
INET_ATON(expr)会将IP地址字符串更改为可用于比较的数字地址。
http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_inet-aton
SELECT * FROM ranges WHERE INET_ATON(ipaddress_s)<INET_ATON('4.100.159.0') AND INET_ATON(ipaddress_e)>INET_ATON('4.100.159.5')