问题
I have a table with a unique key for two columns:
CREATE TABLE `xpo`.`user_permanent_gift` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`fb_user_id` INT UNSIGNED NOT NULL ,
`gift_id` INT UNSIGNED NOT NULL ,
`purchase_timestamp` TIMESTAMP NULL DEFAULT now() ,
PRIMARY KEY (`id`) ,
UNIQUE INDEX `user_gift_UNIQUE` (`fb_user_id` ASC, `gift_id` ASC) );
I want to insert a row into that table, but if the key exists, to do nothing! I don\'t want an error to be generated because the keys exist.
I know that there is the following syntax:
INSERT ... ON DUPLICATE KEY UPDATE ...
but is there something like:
INSERT ... ON DUPLICATE KEY DO NOTHING
?
回答1:
Yes, use INSERT ... ON DUPLICATE KEY UPDATE id=id
(it won't trigger row update even though id
is assigned to itself).
If you don't care about errors (conversion errors, foreign key errors) and autoincrement field exhaustion (it's incremented even if the row is not inserted due to duplicate key), then use INSERT IGNORE
.
回答2:
HOW TO IMPLEMENT 'insert if not exist'?
1.REPLACE INTO
delete then insert new entry if there is entry matches unique key
or primary key
pros: simple.
cons: 1. too slow. 2. auto-increment key will increase.
2.INSERT IGNORE
pros: simple.
cons: 1. auto-increment key will still increase. 2. some other errors will be ignored such as data conversion error.
3.INSERT ... ON DUPLICATE KEY UPDATE
pros: auto-increment key will NOT increase.
cons: looks relatively complex.
回答3:
Use ON DUPLICATE KEY UPDATE ...
,
Negative : because the UPDATE
uses resources for the second action.
Use INSERT IGNORE ...
,
Negative : MySQL will not show any errors if something goes wrong, so you cannot handle the errors. Use it only if you don’t care about the query.
来源:https://stackoverflow.com/questions/4596390/insert-on-duplicate-key-do-nothing