mysql查询,用于根据时间戳识别和删除重复项

时间:2012-03-09 18:52:13

标签: mysql

我正在尝试构建一个mysql查询,以列出从单个表中具有重复列b的所有列a。诀窍是我在行上有一个时间戳,所以我需要基本上识别哪个是重复的旧版本,所以我可以删除它。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:3)

只是示例 - 此查询返回重复的帖子,现在您只需要执行删除

id| title     | text_desc          | created 
-------------------------------------------------------
1 | The title | description here   |2012-02-21 10:58:58
2 | The title | description here 1 |2012-02-21 10:58:58
3 | The title | description here 3 |2012-02-21 10:58:58

    select bad_rows.*
     from posts as bad_rows
      inner join (
       select title, MIN(id) as min_id
          from posts
           group by title
             having count(*) > 1
          ) as good_rows on good_rows.title = bad_rows.title
            and good_rows.min_id <> bad_rows.id;

这是返回行

id| title     | text_desc          | created 
-------------------------------------------------------
2 | The title | description here 1 |2012-02-21 10:58:58
3 | The title | description here 3 |2012-02-21 10:58:58

答案 1 :(得分:3)

这是您的查询:

DELETE FROM tablename
WHERE id IN
(SELECT t1.id
 FROM tablename t1
 JOIN tablename t2
   ON t2.cola = t1.cola AND t2.colb = t1.colb
   AND t2.timecol > t1.timecol
 WHERE t1.cola = t1.colb)

SELECT语句返回cola = colb的记录,以及其他具有较晚日期的匹配行。 DELETE语句删除SELECT返回的所有记录。

如果您要删除重复的cola,那么这就是查询:

DELETE FROM tablename
WHERE id IN
(SELECT t1.id
 FROM tablename t1
 JOIN tablename t2
   ON t2.cola = t1.cola
   AND t2.timecol > t1.timecol)

答案 2 :(得分:0)

SELECT FOOCODE,COUNT(*) AS DUPS
FROM TABLE
GROUP BY FOOCODE
HAVING COUNT(FOOCODE)>1;

以上查询将返回所有重复项。这就是您要找的内容吗?