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
Make a unique index on fields a,b,c.
ALTER TABLE `table` ADD UNIQUE (
`a` ,
`b` ,
`c`
);
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'
);
Make the three columns composite key.
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.