【发布时间】:2013-05-06 09:10:58
【问题描述】:
我有一个记录对我网站的访问的博客:
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
我想知道我是否可以像在 C# 例程中那样使用一个 sql 而不是两个 sql 来生成上表?我尝试使用子选择和连接,但每次我都被“ip小于x order by ip desc limit 1”部分所抛弃。希望在这里得到 SQL 专家的任何指点。
【问题讨论】: