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

假装没事ソ 提交于 2019-11-29 23:48:54

问题


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(*) from table where col1='var1' AND col2='var2' AND col3='var3' AND col4='var4' AND col5='var5')>0) then
    combination of vars exist in record - do a thing;
ELSE
    combination of vars does not exist in record - insert record;
END IF;

I should have thought CASE would suit this but for life of me I'm unable to think of the correct syntax. I'd use unique indexes but every one of the columns needs to allow duplicates, it's only a matching combination of all the columns that needs to be unique, not the fields themselves.

I'm told using a composite key across all the columns would avoid duplicate inserts but from what I gather I need to use a different insert then.

Short version: In MySQL, how do I insert new row only if an exact specified match of columns is not found in an existing row.

Any advice or suggestions would be greatly appreciated.


回答1:


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.



来源:https://stackoverflow.com/questions/17956455/mysql-only-insert-new-row-if-combination-of-columns-which-allow-duplicates-is

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