Find duplicate entry in mysql and update first duplicate with last duplicate value

I have a table like this.

ID    Name     Tag    
1     Orange   tea     
2     Pear     light    
3     Apple    tea
4     Juice    tea
5     Cocoa    baseball
6     Camera   baseball

What I want to do is strings having duplicate TAGS, I want to update the name FIRST having the most recent event.

So, in the above example, I would like to update the name ID 1 from Orange to Juice and delete the rest (# 3, # 4) And update the ID 5 from Cocoa to the camera and delete # 6.

How do I do this using MySQL with PHP? Or is it possible to just do it in MySQL?

Thank!

+3
source share
1 answer

For the query, UPDATEwe need to get the identifier min and max for each tag, only if there are duplicate lines:

UPDATE table t
  JOIN (
    SELECT MinID, b.Name LatestName
    FROM table b
    JOIN (
      SELECT MIN(ID) MinID, MAX(ID) MaxID
      FROM table
      GROUP BY tag
      HAVING COUNT(*) > 1
    ) g ON b.ID = g.MaxID
  ) rs ON t.ID = rs.MinID
SET t.Name = LatestName;

DELETE , :

DELETE t.*
FROM table t
  LEFT JOIN (
    SELECT MIN(ID) MinID
    FROM table
    GROUP BY tag
  ) g ON t.ID = g.MinID
WHERE g.MinID IS NULL;
+4

All Articles