我有一个博客,可以访问我的网站:
Table weblog
id logdate browser ipaddr inet_aton_ip
1 2013-05-01 Chrome 42.61.66.124 708657788
2 2013-05-01 Chrome 217.9.192.99 3641294848
3 2013-05-02 Firefox 77.79.58.77 1297037901
...etc...
我下载了ip2nation数据库,它允许我根据inet_aton_ip值查找国家/地区:
mysql> select * from ip2nation where ip<708657788 order by ip desc limit 1;
+-----------+---------+
| ip | country |
+-----------+---------+
| 708575232 | sg |
+-----------+---------+
mysql> select * from ip2nation where ip<3641294848 order by ip desc limit 1;
+------------+---------+
| ip | country |
+------------+---------+
| 3641286656 | uk |
+------------+---------+
... and so on ...
ip2nation中的ip列标记了IP边界,因此搜索不准确,即相等的比较不起作用。这种结构是有意义的,对于像42.61.66.x这样的子网,它们不必列出255个类似的条目。
使用C#例程,如
DataTable dt = [a sql function to select * from weblog]
foreach (DataRow row in dt.Rows)
{
long ipnum = int.Parse(row["inet_aton_ip"].ToString());
string cty = [a sql function to select country using ipnum]
}
我可以得到下表:
id logdate browser ipaddr inet_aton_ip country
1 2013-05-01 Chrome 42.61.66.124 708657788 sg
2 2013-05-01 Chrome 217.9.192.99 3641294848 uk
3 2013-05-02 Firefox 77.79.58.77 1297037901 lt
我想知道我是否可以使用一个sql而不是两个sqls来生成上面的表,就像在C#例程中一样?我尝试使用子选择和连接,但每次我被“ip less than x order by ip desc limit 1”部分抛弃。非常感谢SQL专家提供的任何指示。
答案 0 :(得分:0)
如果我们有ip2nation
表,那么您可以像这样加入两个表:
SELECT w.*, ip.country
FROM weblog w
JOIN ip2nation ip
ON w.inet_aton_ip = ip.ipp
输出:
╔════╦════════════════════════════╦═════════╦══════════════╦══════════════╦═════════╗
║ ID ║ LOGDATE ║ BROWSER ║ IPADDR ║ INET_ATON_IP ║ COUNTRY ║
╠════╬════════════════════════════╬═════════╬══════════════╬══════════════╬═════════╣
║ 1 ║ May, 01 2013 00:00:00+0000 ║ Chrome ║ 42.61.66.124 ║ 708657788 ║ sg ║
║ 2 ║ May, 01 2013 00:00:00+0000 ║ Chrome ║ 217.9.192.99 ║ 3641294848 ║ uk ║
║ 3 ║ May, 02 2013 00:00:00+0000 ║ Firefox ║ 77.79.58.77 ║ 1297037901 ║ lt ║
╚════╩════════════════════════════╩═════════╩══════════════╩══════════════╩═════════╝
答案 1 :(得分:0)
您可以使用country
直接加入表ip2nation
中的INNER JOIN
。
SELECT a.*. b.country
FROM weblog a
INNER JOIN ip2nation b
ON a.inet_aton_ip = b.ipp
WHERE b.ipp < 708657788
order by b.ipp
要进一步了解联接,请访问以下链接: