【问题标题】:How can I delete all rows with duplicates in one column using MySQL?如何使用 MySQL 删除一列中所有重复的行?
【发布时间】:2016-04-28 18:39:22
【问题描述】:

我有一个表,其中一列标题中有重复值,因此标题列有多行具有相同的值。

我想删除除标题相同的所有重复项。

我可以执行哪种查询来完成此操作?

  Title     Subject             Description               Created_at
Something  Somethingsubject    Somethingdescription       2016-04-13 16:37:10  
Something  Anothersubject      Anotherdescription         2016-04-11 16:37:10
Something  Thirdsubject        Thirdsubject               2016-04-14 16:37:10
NumberTwo  NumberTwoSubject    NumberTwoSubject           2016-04-12 16:37:10
NumberTwo  AnotherNumberTwo    AnotherNumberTwoDescripti  2016-04-15 16:37:10

我想删除所有重复的,只留下一条,最好是最旧的记录,这样剩下的记录就是:

Title        Subject            Description            Created_at
Something  Anothersubject     Anotherdescription    2016-04-11 16:37:10
NumberTwo  NumberTwoSubject    NumberTwoSubject     2016-04-12 16:37:10

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    你可以自加入DELETE:

    DELETE t1
    FROM mytable t1
    JOIN (SELECT Title, MAX(Created_at) AS max_date
          FROM mytable
          GROUP BY Title) t2
    ON t1.Title = t2.Title AND t1.Created_at < t2.max_date   
    

    Demo here

    【讨论】:

      【解决方案2】:

      出于显而易见的原因,首先进行备份,但这应该可以:

      delete from your_table where id not in (select id from your_table group by title) 
      

      其中id 是存储your_table 主键的列

      【讨论】:

      • 至少你没有解决“只留下一个,最好是最旧的记录”的要求。另外,如果那里没有“id”怎么办。
      • 毫无疑问,您总是可以提出更好的解决方案
      • 对不起,没有冒犯的意思。只是试图理解答案。
      • 对不起,我把它当作一个:)
      【解决方案3】:

      我的想法是将结果导出到新表中。然后用新的替换旧的。优点是 1.您可以检查结果是否是您想要的。 2.您不会丢失原始数据

      create table new_mytable select * from (select * from mytable order by created_at) as b group by b.title
      

      【讨论】:

        【解决方案4】:
        DELETE * FROM table WHERE Title ="Something" and Subject <> "Somethingsubject"
        

        在某些版本的sql中不等于是!=

        【讨论】:

        • 这个答案……很有趣。
        • @EthanF。我同意,这个答案肯定会提供一些工作保障,因为在你的主管阅读之前可能会有未来的工作量
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-11-19
        • 1970-01-01
        • 2015-05-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多