在计算完订单的总金额后,我试图更新表格(订单),我成功地计算了总金额,但是我找不到使用结果更新表格的方法。
代码我成功计算了总金额:
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;
结果: total amount
我尝试更新表格(订单)的代码:
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
这是表格“ orders”:
答案 0 :(得分: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
中。
答案 1 :(得分:0)
请尝试此答案。
UPDATE o
SET o.total = t1.total
(SELECT o.orderid, SUM(od.quantity * d.price) AS total
FROM dish AS d
JOIN ordersdish AS od ON od.dishid = d.dishid
JOIN orders AS o ON o.orderid = od.orderid
GROUP BY orders.orderid) t1
WHERE o.orderid = t1.orderid;