0

I have 2 entries in mysql database which has duplicate entries under 'hwaddr' column as shown in the added screenshot.

how do i search for duplicates based on 'hwaddr' column and leave only the most up2date one based on 'timestamp' column? (delete the old one)

mysql data screenshot

Asaf Magen
  • 862
  • 10
  • 22

3 Answers3

0

Try this to delete:

DELETE FROM `list` WHERE `id`IN (SELECT *
    FROM (SELECT MAX( id )
    FROM `list`
    GROUP BY ip
    HAVING COUNT( ip ) >1) AS e)
Suraj
  • 363
  • 2
  • 16
0

assuming greater number primary key (id) will have latest timestamp, so you can use below query which is more optimized and will delete all duplicate records not just one, excluding latest one.

DELETE b.* 
FROM mytable b 
LEFT JOIN (SELECT MAX(id) FROM mytable GROUP BY hwaddr) a ON a.id=b.id 
WHERE a.id IS NULL;

This is single query command even for production server there can be better options.

Zafar Malik
  • 6,734
  • 2
  • 19
  • 30
0

listing hwaddr duplication

SELECT * FROM `general2` WHERE hwaddr in ( SELECT hwaddr FROM general2 GROUP BY hwaddr HAVING COUNT( * ) >1 )

listing what will be deleted

select t1.* FROM general2 t1, general2 t2 WHERE t1.hwaddr=t2.hwaddr  AND t1.timestamp < t2.timestamp 

deleting by hwaddr leaving the most updated by timestamp.

DELETE t1 FROM general2 t1, general2 t2 WHERE t1.hwaddr=t2.hwaddr  AND t1.timestamp < t2.timestamp 
Asaf Magen
  • 862
  • 10
  • 22