使用表连接的Mysql更新 - 使用其他表的字段的总和更新一个表的字段

时间:2010-11-18 07:17:58

标签: mysql join group-by sum

我有两张表OrdersOrder_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

如何在一个查询中执行此操作?

由于

1 个答案:

答案 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

<击>