I have an ordering system in place and one of the fields for customers is used to store the number of orders they've placed. This field occasionally gets out of sync due to orders being voided, deleted, etc, so I occassionally need to run a program to resync the order counts.
Right now I'm running one query to pull all the users, then looping through each user and using another query to count their number of orders, then running a final query to update the "num_orders" field before moving to the next user. Needless to say with 20,000+ users, it's not very efficent. Without having MySQL 4.1 to do subqueries, is there any more efficient way to do this? Any thoughts are greatly appreciated. TIA.
The two tables tables used are (showing only relevant fields):
users
- user_id
- num_orders
orders
- order_id
- user_id