简体   繁体   English

使用 select 和从另一个表更新表

[英]Updating table with select sum from another table

I have two tables: orders and order_items.I need to update the column xpto_spent on orders table with the sum of the total spent with items of the brand XPTO (items described in order_items table).我有两个表:orders 和 order_items。我需要使用 XPTO 品牌商品的总花费总和(在 order_items 表中描述的项目)更新订单表上的 xpto_spent 列。

My current query is returning timeout from mysql server.我当前的查询是从 mysql 服务器返回超时。 The timetou is set to 28800 seconds. timetou 设置为 28800 秒。

UPDATE orders
SET orders.xpto_spent = (
    select 
    format( sum(total), 2) as xpto_spent
    from order_items
    where order_items.brand = "XPTO"
    AND orders.order_id = order_items.order_id
    group by order_items.order_id
);

Any help will be appreciated!任何帮助将不胜感激! Thank you!谢谢!

You would generally do this using join , but you can use a correlated subquery:您通常会使用join执行此操作,但您可以使用相关子查询:

UPDATE orders o
    SET o.xpto_spent = (SELECT SUM(oi.total)
                        FROM order_items oi
                        WHERE oi.brand = 'XPTO' AND
                              oi.order_id = o.order_id
                       );

For this query, you want an index on order_items(order_id, brand, total) .对于此查询,您需要一个关于order_items(order_id, brand, total)的索引。 That will probably speed your query.这可能会加快您的查询速度。

You can join the table orders to the query that returns all the sums from order_items :您可以将表orders加入从order_items返回所有总和的查询:

UPDATE orders o
INNER JOIN (
    SELECT order_id, FORMAT(SUM(total), 2) AS xpto_spent
    FROM order_items
    WHERE brand = 'XPTO'
    GROUP BY order_id
) t ON o.order_id = t.order_id
SET o.xpto_spent = t.xpto_spent

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

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