Mysql Update with table joins - 用其他表字段的总和更新一个表的字段

Mysql Update with table joins - update one table#39;s field with sum of other table#39;s field(Mysql Update with table joins - 用其他表字段的总和更新一个表的字段)
本文介绍了Mysql Update with table joins - 用其他表字段的总和更新一个表的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个表 OrdersOrder_DetailsOrder_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

这篇关于Mysql Update with table joins - 用其他表字段的总和更新一个表的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)
SQL/MySQL: split a quantity value into multiple rows by date(SQL/MySQL:按日期将数量值拆分为多行)