Mysql删除表中重复数据,已解决

如何快速删除数据表中重复【某个字段重复】的数据呢,比如我customer表中有一个cus_nmae字段,如果要删除cus_name字段的重复记录,且保留最小主键【这里customer的主键是cid】,首先想到的sql应该如下:

DELETE
FROM
    customer
WHERE
    cus_name IN (
        SELECT
            cus_name
        FROM
            customer
        GROUP BY
            cus_name
        HAVING
            count(cus_name) > 1
    )
AND cid NOT IN (
    SELECT
        min(cid)
    FROM
        customer
    GROUP BY
        cus_name
    HAVING
        count(cus_name) > 1
);

这样执行会报错:Err] 1093 - You can't specify target table 'customer' for update in FROM clause;原因是:更新数据时使用了查询,而查询的数据又做了更新的条件,mysql不支持这种方式。oracel和msserver都支持这种方式。怎么解决这个问题?再加一层封装,如下:

DELETE
FROM
    customer
WHERE
    cus_name IN (
        SELECT
            cus_name
        FROM
            (
                SELECT
                    cus_name
                FROM
                    customer
                GROUP BY
                    cus_name
                HAVING
                    count(cus_name) > 1
            ) a
    )
AND cid NOT IN (
    SELECT
        min(cid)
    FROM
        (
            SELECT
                min(cid) AS cid
            FROM
                customer
            GROUP BY
                cus_name
            HAVING
                count(cus_name) > 1
        ) b
);

执行以上这条sql语句不会再报错,并且成功删除了cus_name的所有重复记录,只保留了cid最小的那条;大功告成!

你可能感兴趣的:(Mysql)