Is there any way I can insert into, if values not exists in any row?
Let’s say I have a table:
id(auto_increment)|id_user|id_translation
------------------------------------------
39 |5 | 20
-
Tried
INSERT IGNORE INTO `usertranslation`(`id_translation`, `id_user`) VALUES ('20','5')
WHERE not EXISTS (
SELECT * from `usertranslation`
WHERE `id_translation` = '20' AND
`id_user` = '5' )
And similar with replace, but nothing works for me
2
Answers
For prevent duplicates in table the
UNIQUE
constraints must be used.So first you need to change your table like:
After table changed you can use:
Pay attention
INSERT IGNORE
prevent error on attempt to insert duplicates, but increase auto increment field as well.Either use:
which will not insert the new row (without an error) if there are existing constraints which are conflicting with the new row,
or
INSERT
withSELECT
and notVALUES
: