将值从一个表复制到另一个表,其中ID相同

时间:2015-04-23 08:34:05

标签: mysql

我正在处理1000多行的表,其中两列中的数据已损坏(table_corrupted)。幸运的是,我有一个过时的表备份,这两列完整(table_outdated)。所以我想:为什么不直接替换这两列中的值并保留原样?

我们说table_corrupted& table_outdated都有5列:

id(INT),name(TEXT),lat(DOUBLE),lon(DOUBLE),comment(TEXT)

insert into `table_corrupted` (`lat`,`lon`) 
select `lat`,`lon` from `table_outdated`
WHERE `table_corrupted`.`id` = `table_outdated`.`id`;

...导致此错误:“未知列'table_corrupted.id'In Where Clause”

经过一番研究后我发现这是因为SQL从右到左向后评估。说实话,我没有找到解决方案 - 任何建议?我做错了什么?

3 个答案:

答案 0 :(得分:3)

您可以更好地加入表格,只需执行以下查询

即可更新损坏表格中的值
update `table_corrupted`
inner join `table_outdated` on `table_corrupted`.`id` = `table_outdated`.`id`
set `table_corrupted`.`lat`= `table_outdated`.`lat`,
`table_corrupted`.`lon`= `table_outdated`.`lon`

答案 1 :(得分:1)

不要使用插入。使用更新。这个对我有用。

UPDATE `table_corrupted` INNER JOIN `table_corrupted` ON (`table_corrupted`.`id` = `table_outdated`.`id`) 
SET `table_corrupted`.`lat` = `table_outdated`.`lat`, `table_corrupted`.`lon` = `table_outdated`.`lon` 

答案 2 :(得分:1)

您可以使用ON DUPLICATE:

insert into `table_corrupted` (`id`,`lat`,`lon`) 

    select `id`,`lat`,`lon` from `table_outdated`
    on duplicate key update table_corrupted.lat = table_outdated.lat, table_corrupted.lon = table_outdated.lon

或更新:

update table_corrupted,table_outdated
set table_corrupted.lat = table_outdated.lat, table_corrupted.lon = table_outdated.lon
where table_corrupted.id = table_outdated.id
相关问题