2016-02-19 110 views
0

好了,所以我有一個表叫cities的列id,city,state,county,zip_code,urlMYSQL更新表,如果記錄存在

然後我有第二個表稱爲us_url的列:id, url, city, state

cities表有city和獨特的關鍵state以防止重複(因此,如果我導入新記錄,如果城市+狀態組合已存在,則跳過它)。

現在,us_url只是暫時的。我想將該表中的數據複製到cities表中。因此,如果cities中不存在city & state組合,請從us_url表中插入新記錄。如果確實存在,請使用us_url.url值更新cities.url列。

我已經試過這樣:

INSERT INTO cities (id, city, state, county, zip_code, url) 
      VALUES(,us_url.city,us_url.state,,url) 
      ON DUPLICATE KEY UPDATE url=VALUES(url); 

但是,這給了我一個語法錯誤,我甚至不知道這是正確的。

我希望這是有道理的。任何幫助是極大的讚賞。

+0

有太多的','在VALUES ...'VALUES(us_url.city,us_url.state,URL)'。此外,「重複鍵更新」會跳過第一個重複鍵,因此如果您想按組合列過濾,則必須先創建該鍵。 – baao

回答

0
insert into cities (id,city, state,url) (select id,city,state,url from us_url) on duplicate key update url=VALUES(url); 

應該做的伎倆:

mysql> select * from cities; 
+------+------+-------+---------+----------+------+ 
| id | city | state | country | zip_code | url | 
+------+------+-------+---------+----------+------+ 
| 1 | 2 | 3  | 4  | 5  | 6 | 
+------+------+-------+---------+----------+------+ 
1 row in set (0.00 sec) 

mysql> select * from us_url; 
+------+------+------+-------+ 
| id | url | city | state | 
+------+------+------+-------+ 
| 1 | 10 | 2 | 3  | 
| 2 | 11 | 3 | 4  | 
+------+------+------+-------+ 
2 rows in set (0.00 sec) 

mysql> insert into cities (id,city, state,url) (select id,city,state,url from us_url) on duplicate key update url=VALUES(url); 
Query OK, 1 row affected (0.01 sec) 
Records: 2 Duplicates: 0 Warnings: 0 

mysql> select * from cities; 
+------+------+-------+---------+----------+------+ 
| id | city | state | country | zip_code | url | 
+------+------+-------+---------+----------+------+ 
| 1 | 2 | 3  | 4  | 5  | 10 | 
| 2 | 3 | 4  | NULL | NULL  | 11 | 
+------+------+-------+---------+----------+------+ 
2 rows in set (0.00 sec) 

mysql> 
+0

關閉!所以你剛剛添加了從第一列開始的URLS,無論它是否匹配城市。使用你的,這裏是我結束了它的工作:INSERT INTO城市(城市,州,網址)(從us_url選擇城市,州,網址)ON DUPLICATE KEY UPDATE url = VALUES(url); ' – dkeeper09

相關問題