我有一个必须执行以下操作的查询:
如果购物车中有多个商品与同一产品相同,我的查询将停止工作。例如:
product1|quantity X
product2|quantity Y
product1|quantity Z
这是查询(我认为表结构从查询本身非常清楚):
UPDATE ct_products AS P
JOIN ct_shopping_cart_products AS SCP ON (SCP.product = P.id)
SET P.stockQty = P.stockQty + SCP.qty, -- update product stock QTY by QTY from cart products
SCP.qty=0 -- reset QTY on the product in shopping cart
WHERE SCP.cart=0; -- only from carts with ID=0
我不太了解更新中连接的内部工作方式,所以我想这可能是一个非常简单的问题,专家可以轻松解决。
答案 0 :(得分:0)
尝试这个
UPDATE ct_products AS P
JOIN ct_shopping_cart_products AS SCP ON (SCP.product = P.id)
JOIN (SELECT product,cart,SUM(qty) as qty FROM ct_shopping_cart_products
GROUP BY product,cart) AS SCP2 ON (SCP.product = SCP2.product
AND SCP.cart = SCP2.cart)
SET
P.stockQty = P.stockQty + SCP2.qty,
SCP.qty=0
WHERE SCP.cart=0
此查询将使用SCP2.qty
更新,{{1}}是qty GROUPED BY产品和购物车的总和。