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

后端 未结 1 1256
春和景丽
春和景丽 2021-01-03 13:00

Since IF EXISTS isn\'t supported by MySQL I am struggling to think of the syntax for doing something like the following pseudo in MySQL:

IF ((select count(*)         


        
1条回答
  •  孤城傲影
    2021-01-03 13:30

    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.

    0 讨论(0)
提交回复
热议问题