MySQL UPDATE与来自不同表的SELECT SUM

时间:2012-09-23 10:01:31

标签: mysql sql join sql-update

我有两张桌子: ITEMS包含数量和unit_price(id | name | order_id | qt | unit_price) 和表ORDERS

我想UPDATEorders并在orders.total_price sum of multiplications qt*unit_price中输入相同的订单以获得订单的总价。

对items表的SELECT查询非常简单,并且可以为同一order_id中的所有项目提供总和:

SELECT SUM(items.qt*items.unit_price) from items GROUP by items.order_id

但我无法在ORDERS表格中插入此值。我无法做到这一点:

UPDATE orders, items SET orders.total_price = (SELECT SUM(items.qt*items.unit_price)
FROM items GROUP BY items.order_id) WHERE orders.id = items.order_id

返回"Subquery returns more than 1 row"

我发现了一个非常相似的问题here,但答案对我来说也不起作用:

UPDATE orders SET orders.t_price = (SELECT SUM(items.qt*items.unit_price) from items WHERE orders.id = items.order_id)

1 个答案:

答案 0 :(得分:19)

您可UPDATE JOIN两个表:

UPDATE Orders o 
INNER JOIN
(
   SELECT order_id, SUM(qt * unit_price) 'sumu'
   FROM items 
   GROUP BY order_id
) i ON o.id = i.order_id
SET o.total_price = i.sumu
[WHERE predicate]