Mysql Update with table joins - update one table#39;s field with sum of other table#39;s field(Mysql Update with table joins - 用其他表字段的总和更新一个表的字段)
问题描述
我有两个表 Orders 和 Order_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 - 用其他表字段的总和更新一个表的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Mysql Update with table joins - 用其他表字段的总和更新一个表的字段
基础教程推荐
- 无法解决整理冲突 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
