我有下表:
产品
+-------------+------------+
| id_product | quantity |
+-------------+------------+
| 15 | 0 |
| 16 | 1 |
| 17 | 3 |
| 18 | 1 |
+-------------+------------+
另一个表是一个子查询
+------------+-----------+
| id_product | total |
+------------+-----------+
| 15 | 1 |
| 17 | 1 |
| 18 | 4 |
+------------+-----------+
我想做的是在单个更新查询中,用子查询返回的记录更新表产品,求和,我可以从子查询中获取一个或多个记录。
+-------------+------------+
| id_product | quantity |
+-------------+------------+
| 15 | 1 |
| 16 | 1 |
| 17 | 4 |
| 18 | 5 |
+-------------+------------+
我试图进行此更新查询,但它没有执行我想要的操作。
UPDATE product p
INNER JOIN (
SELECT id_product, count(*) as total
FROM othertable
GROUP BY id_product
) c ON p.id_product = c.id_product
SET p.quantity = c.total;
______ EDIT ______
UPDATE product p
INNER JOIN (
SELECT id_product, count(*) as total
FROM othertable
GROUP BY id_product
) c ON p.id_product = c.id_product
SET p.quantity = p.quantity + c.total