How to prevent Duplicate records from my table Insert ignore does not work here

前端 未结 3 1564
情书的邮戳
情书的邮戳 2020-12-05 19:54
mysql> select * from emp;

    +-----+---------+------+------+------+
    | eno | ename   | dno  | mgr  | sal  |
    +-----+---------+------+------+------+
    |          


        
相关标签:
3条回答
  • 2020-12-05 20:40

    Create a UNIQUE CONSTRAINT on which you think the duplicacy exist .

    like

    ALTER TABLE MYTABLE ADD CONSTRAINT constraint1 UNIQUE(column1, column2, column3)
    
    0 讨论(0)
  • 2020-12-05 20:41

    This will work regardless of whether you clean up your table first (i.e. you can stop inserting duplicates immediately and clean up on separate schedule) and without having to add any unique constraints or altering table in any other way:

    INSERT INTO
        emp (ename, dno, mgr, sal)
    SELECT
        e.ename, 2, 2, 2000
    FROM
        (SELECT 'dlksdgj' AS ename) e
        LEFT JOIN emp ON e.ename = emp.ename
    WHERE
        emp.ename IS NULL
    

    The above query assumes you want to use ename as a "unique" field, but in the same way you could define any other fields or their combinations as unique for the purposes of this INSERT.

    It works because it's an INSERT ... SELECT format where the SELECT part only produces a row (i.e. something to insert) if its left joined emp does not already have that value. Naturally, if you wanted to change which field(s) defined this "uniqueness" you would modify the SELECT and the LEFT JOIN accordingly.

    0 讨论(0)
  • 2020-12-05 20:44

    alter the table by adding UNIQUE constraint

    ALTER TABLE employee ADD CONSTRAINT emp_unique UNIQUE (ename,dno,mgr,sal)
    

    but you can do this if the table employee is empty.

    or if records existed, try adding IGNORE

    ALTER IGNORE TABLE employee ADD CONSTRAINT emp_unique UNIQUE (ename,dno,mgr,sal)
    

    UPDATE 1

    Something went wrong, I guess. You only need to add unique constraint on column ename since eno will always be unique due to AUTO_INCREMENT.

    In order to add unique constraint, you need to do some cleanups on your table.

    The queries below delete some duplicate records, and alters table by adding unique constraint on column ename.

    DELETE a
    FROM Employee a
         LEFT JOIN
         (
            SELECT ename, MIN(eno) minEno
            FROM Employee
            GROUP BY ename
         ) b ON a.eno = b.minEno
    WHERE b.minEno IS NULL;
    
    ALTER TABLE employee ADD CONSTRAINT emp_unique UNIQUE (ename);
    

    Here's a full demonstration

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