2015-04-23 86 views
1

我正在处理两列中的数据已损坏的1000+行表(table_corrupted)。幸运的是,我有一张过时的备份表,其中这两列完好无损(table_outdated)。所以我想:为什么不只是替换这两列中的值,而保持原样?将值从一个表复制到另一个表中相同的ID

比方说table_corrupted & table_outdated都有5列:

id(INT),name(文本),lat(双),lon(双),comment(文本)

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

。此错误的结果:“未知列'table_corrupted.id'In Where子句”

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

+0

你有误诊这一点。尝试查询UPDATE语句(这些可以让您更改现有行中的现有值,而不是插入新行)。 – MatBailie

+0

你完全正确,MatBailie!我很愚蠢:-p – Jonas

回答

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` 
+0

其实,他需要更新声明 – MatBailie

+0

@MatBailie: - 是的,这似乎是正确的。更新了我的答案! –

1

不使用INSERT,UPDATE,在损坏的表中的值。使用更新。这一个为我工作。

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` 
+0

不适用于我:**不是唯一的表/别名:table_corrupted ** - 即使在使用数据库名称后也是如此。但是Rahul Tripathi无论如何都解决了它。非常感谢您的快速解答! – Jonas

+0

这是为我工作。谢谢 –

1

您可以使用重复:

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 
相关问题