开发者

Check if row exists, if not add it [MySQL]

开发者 https://www.devze.com 2023-02-09 15:13 出处:网络
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?

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消