I have a problem in sql, in particular I have to copy data from one table to another. Tables have a 1-N relationship and I should copy a field, for example "weight" from table1 to all weight fields from table2 that are linked to the product. I thought about doing as follows, but it didn't work for me:
insert INTO table2 (weight)
select weight
from table1
where table1.product_source_id = table2.source_id;
Any of you have any idea how this can be done?
You want an update
, not insert
.
A generic approach uses a correlated subquery:
update table2
set weight = (select t1.weight from table1 t1 where t1.product_source_id = table2.source_id);
Specific databases might have other approaches.
In Postgres, this would more commonly use a FROM
clause:
update table2
set weight = t1.weight
from table1 t1
where t1.product_source_id = table2.source_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.