MySQL only insert new row if combination of columns (which allow duplicates) is unique

江枫思渺然 提交于 2019-11-30 16:57:07

Create a composite unique index. This will allow any number of duplicates in the individual fields, but the combination needs to be unique.

CREATE UNIQUE INDEX ix_uq ON test (field1, field2, field3);

...and use INSERT IGNORE to insert if the unique index is not violated. If it is, just ignore the insert.

INSERT IGNORE INTO test (field1,field2,field3) VALUES (1,1,1);

An SQLfiddle for testing.

If you want to insert unless there's a duplicate, and update if there is, you can also use INSERT INTO ... ON DUPLICATE KEY UPDATE;

INSERT INTO test (field1, field2, field3) VALUES (1,1,1)
  ON DUPLICATE KEY UPDATE field4=field4+1;

Another SQLfiddle.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!