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

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

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


        
3条回答
  •  臣服心动
    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.

提交回复
热议问题