SQL Upon finding duplicate key, replace entire entry
I have an insert query for MySQL that looks like this:
INSERT INTO table (foo, bar, fooo, baar, etc) VALUES (?,?,?,?,?)
It is used in a script to migrate some columns and keeps encountering duplicate primary keys. (Old database was awful and poorly maintained).
Is there a way I can just tell it to replace the whole offending row with the current values tossing out the old stuff entirely? I know there is an ON DUPLICATE KEY UPDATE command, but I don't know if it would help me as all I've seen it used for is incrementing.
ANSWER: INSERT INTO table (foo, bar, fooo, baar, etc) VALUES (?,?,?,?,?) ON DUPLICATE KEY UPDATE foo=?, bar=?, fooo=?, baar=?, etc=?
Keep in 开发者_Python百科mind that you have to add the values in the referenced array again to account for the extra question marks.
on duplicate key update
should work, as should a replace
statement.
From MySQL manual:
If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index or PRIMARY KEY, an UPDATE of the old row is performed.
What you said:
Is there a way I can just tell it to replace the whole offending row with the current values tossing out the old stuff entirely?
Conclusion: why don't you just try it? It seems it does exactly what you want.
Edit: Since you haven't provided any examples of what you were trying to do, I'll use some from MySQL's website.
INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
Or if you want something that relates more to real world:
INSERT INTO table(int_field, str_field, float_field) VALUES (15, 'some string', '1.22') ON DUPLICATE KEY UPDATE int_field = 15, str_field = 'some_string', float_field = '1.22';
精彩评论