MySQL删除重复数据

在customers表中, cust_name相同则视为重复的行

MySQL删除重复数据_第1张图片

先尝试:

DELETE FROM customers
WHERE cust_id = (SELECT Max(cust_id)
                    FROM customers
                    GROUP BY cust_name
                    HAVING Count(*) > 1); 
报以下错误: Error Code: 1093. You can't specify target table 'customers' for update in FROM clause

这是因为不能在修改表的同时, 在子查询中SELECT该表, 详见https://www.cnblogs.com/benxiaohaihh/p/5715938.html.

再构造中间表:

DELETE FROM customers
WHERE cust_id IN (SELECT * FROM
                     (SELECT Max(cust_id)
                      FROM customers
                      GROUP BY cust_name
                      HAVING Count(*) > 1) AS c) ;
    报以下错误: Error Code: 1175. You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column To disable safe mode, toggle the option in Preferences -> SQL Editor and reconnect.
这是因为在SQL安全更新模式下, UPDATE/DELETE语句的WHERE子句中没有用到主键.
    使用以下语句关闭SQL安全更新模式
SET SQL_SAFE_UPDATES = 0;
然后语句就可以成功执行了.


你可能感兴趣的:(MySQL)