Combining multiple MySQL UPDATEs
Probably every programmer does this at least once in their lifetime. Suppose you need to write a script that counts how many times each product is shown on an e-commerce website. What do you do? Usually one may come up with such solution:
while(there_are_products) {
show_product();
update_product_display_count_in_the_database(); // UPDATE products SET displays = displays + 1 WHERE product_id = '5';
}
It works, right? Where’s the problem?
The problem is that if you have 500 products displayed, you will have to update each entry individually, basically you’ll have to run 500 queries. That doesn’t seem that efficient to me.
Think for a minute how you could improve this.
Instead we could update everything in one batch. E.g.:
products_to_update = array()
while(there_are_products) {
show_product();
products_to_update.add_to_array(product_id);
}
update_products_in_a_batch(products_to_update); // UPDATE products SET displays = displays + 1 WHERE product_id IN (5, 6, 99, 16, 35)
In other words, use a where clause like WHERE field IN (field_value1, field_value2, … , field_value_n). Basically in this case we would always be running just a single MySQL query. Success?
As an analogy you could take excavation. If you need to move a pile of dirt to another place 200 miles away, are you going to use a shovel and run back and forth each time or are you going to use a truck?
Subscribe via RSS