[SQL] INSERT or UPDATE


Writing time : 2012-12-06 21:27:57

INSERT or UPDATE

When executing an INSERT query, in the case of a Recode that already exists, it may be necessary to perform UPDATE instead of INSERT.
In this case, it is possible to perform SELECT to check whether the corresponding RECORD exists, INSERT only if it does not exist, and UPDATE if it exists, but can also be processed with a single query that executes INSERT or UPDATE.

MySQL


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

If there is a value of 1 in the a field, it is a query that modifies only the c field to c+1 without modifying the a and b fields.

If you want to check not only the a field but also the b field, both a and b must be set to unique.

Previous post

Next post

Other posts in the category