tags:

views:

78

answers:

4

If mysql record with condition exists-update it,else create new record

+1  A: 

Are you looking for INSERT ... ON DUPLICATE KEY UPDATE?

soulmerge
+5  A: 

Is this what you're looking for?

INSERT INTO table (a,b,c) VALUES (1,2,3)
  ON DUPLICATE KEY UPDATE c=c+1;

http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

Mark
That is ok but will only do what the OP wanted if there is a unique index on those columns; it can't be used for arbitrary conditions.
MarkR
+2  A: 

Use REPLACE instead of INSERT.

Mark Byers
+2  A: 

You can use the REPLACE INTO for that with the syntax of INSERT INTO. This way MySQL will invoke an UPDATE whenever there's a fictive constraint violation.

Be aware that this construct is MySQL-specific, so your query ain't going to work whenever you switch from DB.

BalusC