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语句。


声明:本站所有文章和图片,如无特殊说明,均为原创发布。商业转载请联系作者获得授权,非商业转载请注明出处。
随机推荐
Node.js 安装
CSS 滚动条样式修改
Land 主题
Node.js 控制台进度条实现原理
wp_signon() 自定义用户登录函数
Debian11 安装笔记2:编译安装PHP
FFmpeg 修改默认音轨
JavaScript Set 详解