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

2022-01-10 00:00:00 duplicates 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.

相关文章