Check if row exists, if not add it [MySQL]
I need to add a row to a MySQL database table but only if the row doesn't already exist. My database server just went down so I can't test this, but will this work as expected?
INSERT INTO `blocks` (`block_file`,`settings_group`)
VALUES ('announcements','announcement_settings')
WHERE NOT EXISTS (SELECT `block_file`,`settings_group`
FROM `blocks`
开发者_运维百科 WHERE `block_file`='announcements' AND `settings_group`='announcement_settings')
It seems like sound logic. Is this a valid query or is there a better way of doing this?
Just create UNIQUE index on (block_file,settings_group)
columns, and MySQL will never let you insert a row that would duplicate these values.
And to answer the question: No, it will not work at all.
精彩评论