Pregunta

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.

¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top