I'm having a problem updating tables in a MySQL database (InnoDB).
I have three tables
1-orders Table
| orderId | userId | status |
|---|---|---|
| 7 | 4 | bending |
| 8 | 4 | bending |
2- orderedProducts
| orderId | productId | quantity |
|---|---|---|
| 7 | 22 | 1 |
| 7 | 24 | 1 |
| 8 | 22 | 2 |
| 8 | 20 | 1 |
3- products
| productId | quantity | purchased |
|---|---|---|
| 20 | 1 | 3 |
| 22 | 0 | 1 |
| 24 | 1 | 1 |
Ok now when I execute the following query:-
UPDATE
orders JOIN
orderedProduct ON orders.orderId=orderedProducts.orderedId JOIN
products ON products.productId=orderedProducts.productId
SET
products.quantity=products.quantity+orderedProducts.quantity,
products.purchased=products.purchased-orderedProducts.quantity,
orders.status="canceled"
WHERE
orders.userId=4;
Or this
UPDATE
orders, orderedProducts, products
SET
products.quantity=products.quantity+orderedProducts.quantity
products.purchased=products.purchased-orderedProducts.quantity,
orders.status="canceled"
WHERE
orders.userId=4 AND products.productId=orderedProducts.productId;
I expected the result to be like this:-
products
| productId | quantity |
|---|---|
| 20 | 2 |
| 22 | 3 |
| 24 | 2 |
But the result was as follows:-
| productId | quantity |
|---|---|
| 20 | 2 |
| 22 | 1 |
| 24 | 2 |
Does anyone have any idea about what happened?
EDIT:- The problem is solved. Thanks to every body i found the soluatiion from everyone's answer...
UPDATE
orders o JOIN
(
SELECT
orderId , productId , SUM(quantity) as requiredQuantity
FROM
orderedProducts
GROUP BY
productId
) as op ON op.orderId=o.orderId JOIN
products as p ON op.productId=p.productId
SET
p.quantity=p.quantity+op.requiredQuantity,
p.purchased=p.purchased-op.requiredQuantity,
o.status="canceled"
WHERE
o.userId=4;