Tuesday, January 5, 2010

had knew that MySQL could....

It start when i tried to make SQL statement that can update some row in PHP and MySQL, but I didn't want
loops that request update statement to MySQL 
{Ex : for($i=1;$i<5;$i++) mysql_query("update some_table set some_field=some_value where primary_key = $i") },
I thought that it seems expensive (costly), cause it have to send request to DBMS (MySQL "in this way") many times. And I didn't want to make stored procedures or stored function or trigger or something else.
When I was "googling", "Boooom!!! How ashame!!!", at this far my experience with MySQL I didn't know it.

{ Indonesian version :http://faridjauhari.wordpress.com/2009/12/31/multi-update-in-one-sql-statement/ }


Well than, let me put it to an example :

table_produk
============================
id | name          | price
============================
1  | gracia        | 200000
2  | michele       | 400000
3  | arif ( Fira ) | 20000
============================

The sql is :

UPDATE table_produk SET nama = CASE WHEN id = 1 THEN 'Mendy'
                                                                    WHEN id = 2 THEN 'Sharen'
                                                                    WHEN id = 3 THEN 'Maria'
                                                          END,
                                             harga = CASE WHEN id = 1 THEN '500000'
                                                                     WHEN id = 2 THEN '300000'
                                                                     WHEN id = 3 THEN '400000'
                                                           END
                                      WHERE id IN (1,2,3);

But it would be litle labouring when type some loops to construct that SQL, where the name and price was inputs. 

----------- sharing in internet is the nice way to improve -------------------

No comments:

Post a Comment