I have a question regarding UPDATE in mysql.
I have a customer table linked to a customer_orders table. The customer table has a customer_balance field. The customer_orders table has an order_cost field . I want to run a monthly query to add the amounts from the order_cost field to the customer_balance field.
I have tried to use UPDATE and SET but this only works if the customer has one order. Any additional order_cost amounts are not added.
Any ideas on how to do this greatly appreciated.
You want to aggregate before doing the update
. Something like this:
update customer c join
(select customerid, sum(order_cost) as sumoc
from customer_orders co
group by customerid
) co
on c.customerid = co.customerid
set c.customer_balance = c.customber_balance + co.sumoc;
Why taking such a risk with data consistency
select customerid, sum(order_cost) as sumoc
from customer_orders co
group by customerid
This will give you always real-time en consistent data.
If you're having performance issues, consider a (after insert) trigger on the custumer_orders table wich updates the customer balance every time an order is inserted
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.