UPDATE record if present; else INSERT
I want to update a record which may or may not be present in a table. If it 开发者_如何转开发is not present in the database then it will be inserted.
To prevent from select I am using UPDATE
statement first and checking affected_rows > 0
if not then I am inserting this record into the table.
I was wondering if there is a better way to do this?
You could use INSERT ... ON DUPLICATE KEY UPDATE
syntax:
INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
http://dev.mysql.com/doc/refman/4.1/en/insert-on-duplicate.html
The difference between this and REPLACE
(Femaref's answer) is that REPLACE
will delete the old row and then insert a new row if a key is duplicated, while this will update the existing row.
Use Replace
instead of Insert
.
http://dev.mysql.com/doc/refman/5.0/en/replace.html
精彩评论