开发者

mysql replace into alternative

开发者 https://www.devze.com 2023-01-01 04:44 出处:网络
i\'m currently using a replace into statement, I have a unique field which wi开发者_运维问答ll cause it to UPDATE rather than INSERT if it finds a duplicate...

i'm currently using a replace into statement, I have a unique field which wi开发者_运维问答ll cause it to UPDATE rather than INSERT if it finds a duplicate...

Problem is if it finds a duplicate i can't get to update on a few columns, it just wipes the lot.

Is there a similar "one statement" method where I can just UPDATE what I want?

I've found merge into but don't undertsnad the first bit about merge into table using table


You're going to want to use the INSERT...ON DUPLICATE KEY UPDATE syntax.

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

Here's an example that will try to create a record with an id, birthday, and name. If a record with the id field exists, it will do the update specified. The table has lots of other fields like email address, zip code, etc. I want to leave those fields alone if I update. (REPLACE INTO would lose any of that data if I didn't include it in the REPLACE INTO statement.)

INSERT INTO user (userid,birthday,first_name,last_name) 
   VALUES (1234,'1980-03-07','Joe','Smith') 
ON DUPLICATE KEY UPDATE 
   birthday = '1980-03-07',
   first_name = 'Joe', 
   last_name = 'Smith';
0

精彩评论

暂无评论...
验证码 换一张
取 消