9

I have a table with an auto_inc id (primary key). I am trying to avoid the insertion of duplicate rows.

Example of a duplicate row:

id  | field a | field b | field c |
1       4          6         7
2       4          6         7

The key (id) is not duplicate since it is automatically generated by MySQL, but all other fields are identical.

Alex Flom
  • 111
  • 1
  • 1
  • 7

4 Answers4

18

Make a unique index on fields a,b,c.

ALTER TABLE `table` ADD UNIQUE (
`a` ,
`b` ,
`c`
);
Lennart
  • 938
  • 1
  • 9
  • 26
  • but the fields are not unique, for example it is fine to have field a=6 many times, what is not allowed is the combination of same values for a,b,c – Alex Flom Jan 06 '12 at 10:57
  • 3
    That is exactly what this does ;-) Its a combined key, not three separate keys. – Lennart Jan 06 '12 at 11:01
8

You should use ON DUPLICATE KEY UPDATE and declaring the fields as unique .

If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index or PRIMARY KEY, an UPDATE of the old row is performed.

aleroot
  • 66,082
  • 27
  • 164
  • 205
  • but the field is not unique, for example it is fine to have field a=6 many times, what is not allowed is the combination of same values for a,b,c – Alex Flom Jan 06 '12 at 10:56
  • 2
    You should create a compound unique index : http://stackoverflow.com/questions/635937/how-do-i-specify-unique-constraint-for-multiple-columns-in-mysql – aleroot Jan 06 '12 at 10:58
3

You can use this also.

INSERT INTO `tableName` ( `field1`, `field2`,`field3`)
SELECT `field1`, `field2`,`field3` FROM `tableName`
WHERE NOT EXISTS (SELECT 1
    FROM `tableName`
    WHERE 
    `field1` = 'value' AND `field2` = 'value'  AND `field3` = 'value'
    );
Nanhe Kumar
  • 12,767
  • 3
  • 67
  • 60
  • 1
    How could I do with dynamic value?, instead of SELECT 1, something like select * WHERE –  Jun 01 '18 at 14:07
-2

Make the three columns composite key.

Ankur
  • 2,051
  • 21
  • 29
Acn
  • 872
  • 2
  • 9
  • 22
  • @ypercubeᵀᴹ This has been fixed as of 20 June 2013. However, this answer was never needed as Lennart's answer on 6 Jan 2012 10:52 UTC took care of this already! – ReinstateMonica3167040 Jul 12 '18 at 23:25