Jeff Monteiro
Jeff Monteiro

Reputation: 755

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!

Upvotes: 1

Views: 2714

Answers (2)

forpas
forpas

Reputation: 164069

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

Upvotes: 1

Gordon Linoff
Gordon Linoff

Reputation: 1269563

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.

Upvotes: 3

Related Questions