I am inserting some data into a table, but it occasionally clashes with other data in the table (ie. it has the same primary key).
I would like to be able to just overwrite this data if it is there, instead of having mysql send me an error message saying that there is a duplicate primary key. I know that I can just delete these values beforehand, but it would take a somewhat large query. Is it possible to overwrite 开发者_Python百科these values and suppress any warnings, or am I forced to remove these values?Just a little cheatsheet.
Mysql has 3 different scenarios for handling unique key duplicates:
If you want to...
- do nothing - use
INSERT IGNORE
- delete existing and create new - use
REPLACE INTO
- update existing - use
ON DUPLICATE UPDATE
You can use REPLACE INTO in MySQL to do this.
REPLACE INTO table
SET name = 'Treffynnon'
MySQL has a "INSERT ... ON DUPLICATE KEY UPDATE" command. You can find it here: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
INSERT INTO `table` VALUES ('a', 'b') ON DUPLICATE KEY UPDATE `field1`='a', `field2`='b'
Look up "on duplicate key update".
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
You can use replace statement instead of insert. Look at http://dev.mysql.com/doc/refman/5.1/en/replace.html
精彩评论