我有两张表Orders
和Order_Details
Order_Details
个表的order_id
字段充当Orders
表的id_order
表的外键。
我想更新price_total
表的Orders
字段,其中包含Order_Details
表中的价格总和。
我尝试使用以下查询但失败了: -
Update Orders, Order_Details
SET Orders.price_total = sum(Order_Details.price)
WHERE Orders.price_total=0
GROUP BY Order_Details.id_order
错误 -
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'GROUP BY Order_Details.id_order' at line 4
如何在一个查询中执行此操作?
由于
答案 0 :(得分:4)
您可以将其简化为
Update Orders
SET Orders.price_total =
(
SELECT
sum(Order_Details.price)
FROM Order_Details
WHERE
Orders.id_order=Order_Details.order_id
)
WHERE Orders.price_total=0;
<击> 更新进行分组
Update Orders, Order_Details
SET Orders.price_total = sum(Order_Details.price)
WHERE
Orders.price_total=0 AND
Orders.id_order=Order_Details.order_id
GROUP BY Order_Details.id_order
击> <击> 撞击>