MySQL – How to Remove Duplicate Records with Timestamps

MySQL

I have a table in my DB where I keep track of user data. So I have rows like that:

(row_id,user_id, stat1,stat2,..., statN, timestamp)

Now I want to remove all duplicate records, where user_id and stat columns are the same, but only between other rows with different data. So if I have

(row_id, user_id, stat1, stat2, stat3, timestamp)
(1,1,1,0,1,1000)
(2,1,1,1,1,2000)
(3,1,1,1,1,3000)
(4,1,1,0,1,4000)

It should became

(1,1,1,0,1,1000)
(2,1,1,1,1,2000)
(4,1,1,0,1,4000)

And not

(1,1,1,0,1,1000)
(2,1,1,1,1,2000)

So I want to save record progression but remove meaningless duplicates.

Best Answer

delete t1.*
from `table` t1
inner join `table` t2
  on  t1.user_id = t2.user_id 
  and t1.stat1=t2.stat1
  and t1.stat2=t2.stat2
      /* ........... */  
  and t1.statN=t2.statN
  and t1.timestamp>t2.timestamp
left join `table` t3
   on t1.user_id = t3.user_id 
  and t3.timestamp > t2.timestamp 
  and t3.timestamp < t1.timestamp
where t3.user_id is null;

fiddle