好的,我有一个名为cities
的表格,列id,city,state,county,zip_code,url
然后我有第二个名为us_url
的表,其中包含列:id, url, city, state
cities
表具有city
和state
的唯一键以防止重复(因此,如果我导入新记录,如果城市+州组合已经存在,请跳过它)。
目前,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);
但这给了我一个语法错误,我甚至不确定这是否正确。
我希望这是有道理的。非常感谢任何帮助。
答案 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>