2011-01-27 107 views
8

我有兩個表格;Mysql基於從另一個表中選擇更新所有行

mysql> describe ipinfo.ip_group_country; 
+--------------+-------------+------+-----+---------+-------+ 
| Field  | Type  | Null | Key | Default | Extra | 
+--------------+-------------+------+-----+---------+-------+ 
| ip_start  | bigint(20) | NO | PRI | NULL |  | 
| ip_cidr  | varchar(20) | NO |  | NULL |  | 
| country_code | varchar(2) | NO | MUL | NULL |  | 
| country_name | varchar(64) | NO |  | NULL |  | 
+--------------+-------------+------+-----+---------+-------+ 

mysql> describe logs.logs; 
+----------------------+------------+------+-----+---------------------+----------------+ 
| Field    | Type  | Null | Key | Default    | Extra   | 
+----------------------+------------+------+-----+---------------------+----------------+ 
| id     | int(11) | NO | PRI | NULL    | auto_increment | 
| ts     | timestamp | NO |  | CURRENT_TIMESTAMP |    | 
| REMOTE_ADDR   | tinytext | NO |  | NULL    |    | 
| COUNTRY_CODE   | char(2) | NO |  | NULL    |    | 
+----------------------+------------+------+-----+---------------------+----------------+ 

我可以使用IP地址從第一個表中選擇國家代碼:

mysql> SELECT country_code FROM ipinfo.`ip_group_country` where `ip_start` <= INET_ATON('74.125.45.100') order by ip_start desc limit 1; 
+--------------+ 
| country_code | 
+--------------+ 
| US   | 
+--------------+ 

在logs.logs,我把所有的REMOTE_ADDR(IP地址)集,但所有COUNTRY_CODE項是空的。現在,我想使用ipinfo表格適當地填充COUNTRY_CODE。我怎樣才能做到這一點?

謝謝!

回答

9

嘗試

UPDATE logs.logs 
SET COUNTRY_CODE = (
    SELECT country_code 
    FROM ipinfo.ip_group_country 
    WHERE ipinfo.ip_start <= INET_ATON(logs.REMOTE_ADDR) 
    LIMIT 1 
) 
WHERE COUNTRY_CODE IS NULL 

如果失敗說,這樣的REMOTE_ADDR列是同一類型(VARCHAR(20))作爲列類型必須匹配,你必須改變你的logs.logs表ip_cidr表。

8

在單表更新中,您使用update t1 set c1=x where y

在多表更新使用update t1, t2 set t1.c1=t2.c2 where t1.c3=t2.c4

這裏的相關文件http://dev.mysql.com/doc/refman/5.0/en/update.html

你要尋找的是沿(editted)update logs.logs as l, ipinfo.ip_group_country as c set l.COUNTRY_CODE=c.country_code where c.ip_start <= INET_ATON(l.REMOTE_ADDR) order by c.ip_start asc

編輯線的東西:你」在我提供的原始答案中,max()無法正常工作。上面的查詢應該,雖然它可能會比下面提供的答案中的方法更低效。

+0

謝謝。我得到一個錯誤:`mysql> update logs.logs as l,ipinfo.ip_group_country as c set l.COUNTRY_CODE = max(c.country_code)where c.ip_start <= INET_ATON(l.REMOTE_ADDR); 錯誤1111(HY000):無效的組功能使用' – anon 2011-01-27 14:32:46

相關問題