Mysql Update with table joins - 用其他表字段的总和更新一个表的字段
我有两个表 Orders
和 Order_Details
Order_Details
表的 order_id
字段充当 Orders
表的 id_order
表的外键.
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.
我想用 Order_Details
表中的价格总和来更新 Orders
表的 price_total
字段.
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
错误 -
#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
如何在一个查询中完成?
How to do it in one query?
谢谢
推荐答案
可以简化为
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
相关文章