mysql - SQL 使用另一个查询的结果更新表
问题描述
我在计算该订单的总金额后尝试更新表(订单),我成功计算了总金额,但我找不到使用结果更新表的方法。
我成功计算总金额的代码:
SELECT orders.orderid,
SUM(ordersdish.quantity*dish.price) AS total
FROM dish
JOIN ordersdish
ON ordersdish.dishid = dish.dishid
JOIN orders
ON orders.orderid = ordersdish.orderid
GROUP BY orders.orderid;
结果: 总金额
我尝试更新表(订单)的代码:
UPDATE orders
SET total = t1.total
FROM (
SELECT orders.orderid,
SUM(ordersdish.quantity*dish.price) AS total
FROM dish
JOIN ordersdish
ON ordersdish.dishid = dish.dishid
JOIN orders
ON orders.orderid = ordersdish.orderid
GROUP BY orders.orderid
)t1
WHERE orders.orderid = t1.orderid;
MySQL 说:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'from
(select orders.orderid, SUM(ordersdish.quantity*dish.price)as total
from ' at line 3
这是表格“订单”:
解决方案
MySQL 中的正确语法使用JOIN
:
update orders o join
(select od.orderid, SUM(od.quantity * d.price)as total
from dish d join
ordersdish od
on od.dishid = d.dishid
group by od.orderid
) t1
on o.orderid = t1.orderid
set o.total = t1.total;
请注意,orders
子查询中不需要,因为orderid
在orderdish
.
推荐阅读
- java - 用 Gou Hall 算法进行骨架化不起作用
- excel - 尝试为变量赋值时出现 VBA 运行时错误 1004“应用程序定义或对象定义错误”
- c++ - QT如何检查是否按下了键?
- angular - 如何使用 ngx-datatable 动态删除和编辑行
- c# - 单例视图模型 WPF
- javascript - 使用列表更改 html 页面白色事件 onchange
- java - mvn 在运行 junit5 合同测试时返回未找到测试消息
- javascript - 如何设置 scollbar overlay-y 的宽度
- css - Grid-Items(默认按钮)增加了网格容器?
- python - 删除列表中的列表并更改编码