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


声明:本站所有文章和图片,如无特殊说明,均为原创发布。商业转载请联系作者获得授权,非商业转载请注明出处。
随机推荐
JavaScript EventSource 服务器发送事件 Server-Sent Events(SSE)
WordPress 常用的路径
uni-app 实现暗黑模式/夜间模式/深色模式/暗黑主题(DarkMode)的几种方法
SQL 注入的生命力
Debian11 安装笔记3:安装 MySQL 5.7
JavaScript 窗口/文档事件
JavaScript 的历史
WordPress 插件开发