[英]Copy values from one table to another where same ID
我正在處理包含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'在where子句中”
經過一些研究,我發現這是因為SQL是從右到左向后評估的。 老實說,我沒有找到解決方案-有什么建議嗎? 我究竟做錯了什么?
您可以通過執行以下查詢,更好地聯接表並僅更新損壞的表中的值
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`
不要使用插入。 使用更新。 這個為我工作。
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`
您可以使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.