如何使用MySQL删除一列中包含重复项的所有行?

时间:2016-04-28 18:39:22

标签: mysql sql

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

我想删除除标题相同的所有重复项之外的所有副本。

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

  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

4 个答案:

答案 0 :(得分:8)

您可以自行加入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

答案 1 :(得分:1)

首先进行备份,原因很明显,但这应该有效:

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

id是存储your_table

主键的列

答案 2 :(得分:0)

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

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

答案 3 :(得分:-1)

DELETE * FROM table WHERE Title ="Something" and Subject <> "Somethingsubject"
某些版本的sql中的

不等于&lt;&gt;是!=