Avoiding inserting duplicate rows in mySQL

后端 未结 4 2087
刺人心
刺人心 2020-12-09 22:22

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           


        
相关标签:
4条回答
  • 2020-12-09 22:57

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

    ALTER TABLE `table` ADD UNIQUE (
    `a` ,
    `b` ,
    `c`
    );
    
    0 讨论(0)
  • 2020-12-09 23:07

    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'
        );
    
    0 讨论(0)
  • 2020-12-09 23:10

    Make the three columns composite key.

    0 讨论(0)
  • 2020-12-09 23:19

    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.

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