简体   繁体   中英

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).

My current query is returning timeout from mysql server. The timetou is set to 28800 seconds.

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:

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) . That will probably speed your query.

You can join the table orders to the query that returns all the sums from 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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