MySQL 删除多余重复的记录,只保留一条

显示所有重复数据分组

SELECT 
    origin_id
FROM 
    topk88_product
GROUP BY origin_id 
HAVING count(*)>1


删除所有重复

DELETE FROM topk88_product
WHERE origin_id IN (
    SELECT 
        origin_id
    FROM 
        topk88_product
    GROUP BY origin_id 
    HAVING count(*)>1
);

提示:You can't specify target table 'topk88_product' for update in FROM clause;MySQL 不允许查询一个表的时候,又更新同一个表。解决办法是把要更新的几列数据查询出来做为一个临时表,然后筛选更新。


DELETE FROM topk88_product
WHERE origin_id IN (
    SELECT origin_id FROM(
        SELECT origin_id FROM topk88_product GROUP BY origin_id HAVING count(*)>1
    ) t
)


上面操作会把所有重复数据全部删除,可以设置只保留ID最小的那一条数据。

DELETE FROM topk88_product
WHERE origin_id IN (
  SELECT origin_id FROM(
    SELECT origin_id FROM topk88_product GROUP BY origin_id HAVING count(*)>1
  ) t
) 
AND id NOT IN (
  SELECT t2.min_id FROM(
    SELECT min(id) AS min_id FROM topk88_product GROUP BY origin_id HAVING count(*)>1
  ) t2
);


上面是正确的MySQL语句。


修改时间 2021-03-17

真诚赞赏,手留余香
赞赏
随机推荐
阿里云对象存储 OSS 限流超过阈值自动关闭【防破产,保平安】
为什么 PDO 无法捕获异常
物理对齐和视觉对齐
Sequelize 批量导入和批量更新数据
Vue和Ajax的关系,Axios简介
PM2 负载均衡
MySQL 函数 concat、concat_ws 和 group_concat
JS生成 UUID的四种方法
Ecshop二次开发之后台添加新栏目
JS模仿《无限梦魇》中的精灵控制和场景滚动