简体   繁体   中英

Copy values from one table to another where same ID

I am working with a table of 1000+ rows where data in two columns has been corrupted ( table_corrupted ). Luckily I have an outdated backup of that table where these two columns are intact ( table_outdated ). So I thought: Why not just replace the values in those two columns and leave the rest as it is?

Let's say table_corrupted & table_outdated both have 5 columns:

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`;

...results in this error: "Unknown Column 'table_corrupted.id'In Where Clause"

After some research I found out this is because SQL is evaluated backwards, from right to left. To be honest, I did not figure out a solution - any advice? What am I doing wrong?

You can better join the tables and simply update the values in your corrupted table by executing the below query

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`

Dont use insert. Use update. This one worked for me.

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` 

You can use 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

or an update:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM