ON DUPLICATE KEY UPDATE
Sometimes it's not known if the record you are about to insert into MySQL exists or not. You can catch this possible event by using ON DUPLICATE KEY.
Thanks to the ON DUPLICATE KEY UPDATE option in MySQL this can be condensed to the following:
$result = mysql_query("INSERT INTO table_name SET id = $id, a = 2, b = 3 ON DUPLICATE KEY UPDATE a = 2, c = 3");
I prefer the above syntax (using set and writing field = value for each field) but as shown in the MySQL manual, it works with the (field1,field2,field3) VALUES (value1,value2,value3) version as well. Even when using prepared statements this can become a performance issue.
You also have the added value of reducing the query optimizer parsing of this statement so that this is only executed once instead of twice.
Alternative
There is however another method to creating or updating rows. By using mysql_num_rows() the excistence of a record can be verified.
$query = mysql_query("SELECT id FROM table_name WHERE id = $id");
if(mysql_num_rows($query) == 0) {
mysql_query("INSERT INTO table_name (id,a,b) VALUES ($id,2,3)");
} else {
// The record exists, update it.
}
Speed and performance
If MySQL insert encounters a duplicate record it will just update the particular field.
This query is not only going to save your query typing time, but your server is gonna end up bearing a smaller load.
Rewriting your UPDATE/INSERTS to use ON DUPLICATE KEY UPDATE can allow you to take individual statements and rewrite them as you wish.
If you only need one row updated if the row already exists, specify only that row in the UPDATE portion of the query.
Replace would NOT since its pretty much inefficient.
More precisely or by taking an example, you may want to use this query when you want to count how many times a User has logged into your website.
This also prevented lbpool from taking slave servers out of production by 20% (they were no longer falling too far behind replication).
A generic scenario would be that you are inserting data into a table and along with this you want to update a counter which is nothing but a field in the same table in your database.
If you have alot of clients performing INSERTs at the same time on a master server these are serialized and replayed on your slaves. MySQL slave replication is single threaded when it comes to performing SQL statements.
Posted by James on 2010-05-09 in the category " mysql "
