0

I have thousands of records (included duplicate posts) so now I want to delete old records (just leave the latest record) based on date.

My code is given below

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

The problem is that it random records base on ID. I really appreciate your help!

Barmar
  • 741,623
  • 53
  • 500
  • 612
The Hung
  • 309
  • 4
  • 18

2 Answers2

1

If you want to base it on date, you should use MAX(date) in the subquery.

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
Barmar
  • 741,623
  • 53
  • 500
  • 612
-1

Just create the SELECT query of posts you want to delete and put and in a subselect:

DELETE FROM dle_post WHERE id IN (SELECT id FROM dle_post WHERE ... )

This is more readable and maintainable.

Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195