How to update a cache value in table1 by JOINing and SUMing values in a sub-table?
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 periodicall开发者_Python百科y 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.
update o
set balance = op.amt
from orders o
left join (select order_id, sum(amount) amt from order_payments group by order_id) op
on o.id = op.order_id
精彩评论