MySQL删除旧记录

时间:2017-04-08 08:43:37

标签: mysql

我有数千条记录(包含重复的帖子)所以现在我想根据日期删除旧记录(只留下最新记录)。

我的代码如下:

class A {
public:
  template<class U> bool can_be(const U*)
{
return can_be<U>();
}
  template<class U> MyHandle<U> as(const U*)
{
return as<U>();
}

  template<class U> bool can_be();
  template<class U> MyHandle<U> as();
};

template<class T>
    template<class U>
    struct MyHandle<T>::can_be_ref<U, true>
    {
        bool operator()(const MyHandle<T> * ptr, const U* uptr) const
        {
            return ptr->get_member_reference()->can_be(uptr);
        }
    };

    template<class T>
    template<class U>
    struct MyHandle<T>::as_ref<U, true>
    {
        MyHandle<U> operator()(const MyHandle<T> *ptr, const U* uptr) const
        {
            return ptr->get_member_reference()->as(uptr);
        }
    };

问题在于它是基于DELETE a.* FROM dle_post AS a INNER JOIN ( SELECT title, MIN( id ) AS min_id FROM dle_post GROUP BY title HAVING COUNT( * ) > 1 ) AS b ON b.title = a.title AND b.min_id <> a.id 的随机记录。我真的很感谢你的帮助!

2 个答案:

答案 0 :(得分:1)

如果您希望以日期为基础,则应在子查询中使用MAX(date)

DELETE a.*
FROM dle_post AS a
   INNER JOIN (
      SELECT title, MAX(date) AS maxdate
      FROM dle_post
      GROUP BY title
      HAVING COUNT( * ) > 1
   ) AS b 
ON b.title = a.title
AND a.date < b.maxdate

答案 1 :(得分:-1)

只需创建要删除的帖子的DELETE FROM dle_post WHERE id IN (SELECT id FROM dle_post WHERE ... ) 查询,并将其放入子选择中:

statistics

这更具可读性和可维护性。