如何从 MySQL 表中删除重复的行

How to delete duplicate rows from a MySQL table(如何从 MySQL 表中删除重复的行)
本文介绍了如何从 MySQL 表中删除重复的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 MySQL 表,例如:

I have a MySQL table like:

ID, Col1, Col2, Col3, Col4, etc...

ID 是一个主键,自表创建以来一直有效.

ID is a primary key and has been working since the table's creation.

我想要做的是删除所有其他列都相同的记录.

What I want to do is delete all but one records where all the other columns are identical.

推荐答案

DELETE DupRows.*
FROM MyTable AS DupRows
   INNER JOIN (
      SELECT MIN(ID) AS minId, col1, col2
      FROM MyTable
      GROUP BY col1, col2
      HAVING COUNT(*) > 1
   ) AS SaveRows ON SaveRows.col1 = DupRows.col1 AND SaveRows.col2 = DupRows.col2
      AND SaveRows.minId <> DupRows.ID;

当然,您必须将所有三个位置的 col1、col2 扩展到所有列.

Of course you have to extend col1, col2 in all three places to all columns.

我刚刚从我保留并重新测试的脚本中提取了它,它在 MySQL 中执行.

I just pulled this out of a script I keep and re-tested, it executes in MySQL.

这篇关于如何从 MySQL 表中删除重复的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)
SQL/MySQL: split a quantity value into multiple rows by date(SQL/MySQL:按日期将数量值拆分为多行)