记录存在时的MYSQL更新表

时间:2016-02-19 16:39:59

标签: mysql

好的,我有一个名为cities的表格,列id,city,state,county,zip_code,url

然后我有第二个名为us_url的表,其中包含列:id, url, city, state

cities表具有citystate的唯一键以防止重复(因此,如果我导入新记录,如果城市+州组合已经存在,请跳过它)。

目前,us_url只是暂时的。我想将该表中的数据复制到cities表。如果是city& state中不存在cities组合,插入us_url表中的新记录。如果确实存在,请使用cities.url值更新us_url.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);

但这给了我一个语法错误,我甚至不确定这是否正确。

我希望这是有道理的。非常感谢任何帮助。

1 个答案:

答案 0 :(得分: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>