从另一个 table 更新 table 中的数据

updating data in a table from another table

我有两个table:
cart_item

id, session_id, product_id, quantity
1   1           2           5
2   1           3           5

product

id, quantity
2   50
3   75

如何根据cart_itemtable中的数据正确更新producttable中的数据?我想更新 table product.
中的产品数量 通过更新 product 中的数据,我将删除 table cart_item 中的所有产品。 这是更新数据时我想得到的:
product

id, quantity
2   45
3   70

也许像下面这样的查询

update p
set p.quantity = p.quantity - sum(ci.quantity)
from product p
join cart_item ci
on ci.product_id=p.id
group by p.id

你可以尝试用UPDATE ... JOIN来计算这个值

UPDATE product p 
JOIN cart_item ci ON ci.product_id = p.id
SET p.quantity = p.quantity - ci.quantity

sqfliddle