简体   繁体   English

MySQL UPDATE与来自不同表的SELECT SUM

[英]MySQL UPDATE with SELECT SUM from different table

I have two tables: ITEMS with quantities and unit_price (id | name | order_id | qt | unit_price) and table ORDERS . 我有两个表: ITEMS的数量和unit_price(id | name | order_id | qt | unit_price)和表ORDERS

I want to UPDATE table orders and place in orders.total_price sum of multiplications qt*unit_price for the same orders to get total price of the order. 我想UPDATEorders并将orders.total_price sum of multiplications qt*unit_price放在相同的订单中以获得订单的总价。

The SELECT query on the items table is quite simple and works fine giving sums for all items within the same order_id: items表上的SELECT查询非常简单,并且可以为同一order_id中的所有项目提供总和:

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

but I can't insert this value in my ORDERS table. 但是我不能在我的ORDERS表中插入这个值。 I couldn't make this work: 我无法做到这一点:

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

it returns "Subquery returns more than 1 row" 它返回"Subquery returns more than 1 row"

I found a very similar question here but the answer didn't work for me as well: 我在这里发现了一个非常相似的问题但答案对我来说也不起作用:

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

You can UPDATE with JOIN ing the two tables: 您可以通过JOIN两个表来UPDATE

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM