七度&光 2011-01-13 20:58 采纳率: 22.2%
浏览 287
已采纳

除了 MySQL 中的重复行之外,删除所有重复行? [重复]

Possible Duplicate:
Remove duplicate rows in MySQL

How would I delete all duplicate data from a MySQL Table?

For example, with the following data:

SELECT * FROM names;

+----+--------+
| id | name   |
+----+--------+
| 1  | google |
| 2  | yahoo  |
| 3  | msn    |
| 4  | google |
| 5  | google |
| 6  | yahoo  |
+----+--------+

I would use SELECT DISTINCT name FROM names; if it were a SELECT query.

How would I do this with DELETE to only remove duplicates and keep just one record of each?

转载于:https://stackoverflow.com/questions/4685173/delete-all-duplicate-rows-except-for-one-in-mysql

  • 写回答

2条回答 默认 最新

  • 斗士狗 2011-02-16 12:30
    关注

    Editor warning: This solution is computationally inefficient and may bring down your connection for a large table.

    NB - You need to do this first on a test copy of your table!

    When I did it, I found that unless I also included AND n1.id <> n2.id, it deleted every row in the table.

    1. If you want to keep the row with the lowest id value:

      DELETE n1 FROM names n1, names n2 WHERE n1.id > n2.id AND n1.name = n2.name
      
    2. If you want to keep the row with the highest id value:

      DELETE n1 FROM names n1, names n2 WHERE n1.id < n2.id AND n1.name = n2.name
      

    I used this method in MySQL 5.1

    Not sure about other versions.


    Update: Since people Googling for removing duplicates end up here
    Although the OP's question is about DELETE, please be advised that using INSERT and DISTINCT is much faster. For a database with 8 million rows, the below query took 13 minutes, while using DELETE, it took more than 2 hours and yet didn't complete.

    INSERT INTO tempTableName(cellId,attributeId,entityRowId,value)
        SELECT DISTINCT cellId,attributeId,entityRowId,value
        FROM tableName;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了