Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql delete rows with duplicate dates keeping the latest one

In my mysql database I have a table similar to this one:

Data                |Val  | Val2 
2016-11-11 14:48:38 |10   | 20
2016-11-11 14:48:38 |30   | 40
2016-11-06 11:48:38 |50   | 60
2016-11-08 19:48:38 |70   | 80
2016-11-06 11:48:38 |90   |100
2016-11-16 10:13:37 |100  |110
2016-11-16 10:13:37 |120  |130
2016-11-16 10:16:43 |140  |150
2016-11-16 10:13:37 |140  |150

Sometimes in my database I can have duplicate dates (data) but different values for (val,val2), I wish to delete all the rows with duplicate data except the last one inserted on the database. How can I achieved that? For example, for the table above the result that I want is:

Data             |Val |Val2
11/11/2016 14:48 |30  |40
08/11/2016 19:48 |70  |80
06/11/2016 11:48 |90  |100
16/11/2016 10:16 |140 |150
16/11/2016 10:13 |140 |150

I was using sqlite3 and I could achieve what I want by doing

delete from table where rowid not in (select max(rowid) from table group by data)

but I couldn't find the equivalent for mysql.

like image 655
eriast Avatar asked Jan 29 '26 01:01

eriast


1 Answers

This will delete the smallest Val when have same date

SQL DEMO

DELETE t1 
FROM Table1 t1
JOIN Table1 t2
  ON t1.`Data` = t2.`Data`
 AND t1.`Val` < t2.`Val`;

OUTPUT

enter image description here

like image 113
Juan Carlos Oropeza Avatar answered Jan 31 '26 14:01

Juan Carlos Oropeza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!