开发者

Mysql Update with table joins - update one table's field with sum of other table's field

I have two tables Orders and Order_Details Order_Details tables's order_id field acts as foreign key to Orders table's id_order table.

I want to update the price_total field of Orders table with summation of prices from Order_Details table.

I tried with the following query but failed:-

Update Orders, Order_Details
  SET  Orders.price_total = sum(Order_Details.price)
 WHERE Orders.price_total=0
 GROUP BY Order_Details.id_order

Error -

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for th开发者_StackOverflow中文版e right syntax to use near 'GROUP BY Order_Details.id_order' at line 4

How to do it in one query?

Thanks


You can simplify it to

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;

updated for grouping

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜