[英]MySQL: How to select and display ALL rows from one table, and calculate the sum of a where clause on another table?
[英]How to calculate the sum in one table and then insert into another table?
我有兩張桌子。 第一張表:順序
|id |total|
|A001 | |
|A002 | |
第二張表:商品
|id |price|order_id|
|B001 |100 |A001 |
|B002 |200 |A001 |
|B003 |300 |A002 |
現在如何寫SQL語句計算goods表中有相同order_id的SUM價格,然后插入到order表的total列中,像這樣:
|id |total|
|A001 |300 |
|A002 |300 |
Update O
SET O.total = t.Sum_Of_Price
FROM Order AS O
INNER JOIN
(
Select order.id as ID, sum(goods.price) as Sum_Of_Price
from goods
INNER JOIN order
ON order.id = goods.order_id
group by order.id
) t
ON O.id = t.id
with temp(id, total) as (select order_id, sum(price) from goods group by order_id) update order
o join temp t on o.id = t.id set o.total = t.total;
select * 來自order
;
我發現'order'是sql中的關鍵字,所以我將第一個表名更改為'orders'。
update orders 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
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.