现在我有两个表
表1:order
|id | total|
|A001 | |
|A002 | |
表2:goods
|id | price | order_id |
|B001 | 100 | A001 |
|B002 | 200 | A001 |
|B003 | 300 | A002 |
我该怎么样才能将表2(goods)中的price数据根据order_id求和并插入到表1中?
像这样:
|id | total |
|A001 | 300 |
|A002 | 300 |
对已经存在的行的部分字段进行修改,这个叫更新,不叫插入。
然后,你需要说明你使用的是什么数据库,不同数据库支持的写法是有所区别的。
以下是在oracle数据库中的写法
update order a set total=(select sum(price) from goods b where a.id=b.order_id)
where exists (select 1 from goods b where a.id=b.order_id);
或者用plsql游标循环
begin
for rec in (select order_id, sum(price) s from goods group by order_id) loop
update order a set a.total=rec.s where a.id=rec.order_id;
end loop;
end;
insert into order select order_id,sum(price) from goods group by order_id