loading
Please wait while loading...
Back If exists update else insert with only MySQL

Today learn a new method on MySQL. On programing, we always need to judge a record is exists or not, update when exists else insert. I'm always using PHP to do that before, but today I find the that MySQL already have a method to do so. For example, if a table contain three colum a,b,c and a is the unique key or primary key, you can use the following statment to do an update exists else insert.

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

This will insert a new record when the table hasn't a record a=1 else the record will update c=c+1

Comments
comments powered by Disqus