I have an orders table:
id | name | date | total | balance
and an order_payments table:
id | order_id | amount | date
I’d like to update my Orders table ‘balance’ column periodically by summing the ‘amount’ column of order_payments and subtracting from the ‘total’. Is there a way to do this with one Update statement by JOINing with order_payments and taking the SUM of ‘amount’? Something like:
UPDATE orders
LEFT JOIN order_payments ON order_payments.order_id = orders.id
SET balance = SUM(order_payments.amount)
I’m more of a MSSQL user, but I’m pretty sure something similar to the following should work in mysql as well. You might have to slightly fidget with the syntax. The general idea is that you can’t update a table with aggregate values directly, so you use a derived table to do the aggregation, join to it, and then update.