开发者

Find duplicate mysql record and update first duplicate with last duplicate value

开发者 https://www.devze.com 2023-02-17 02:30 出处:网络
i have a table like this. IDNameTag 1Orangetea 2Pearlight开发者_如何学JAVA 3Appletea 4Juicetea 5Cocoabaseball

i have a table like this.

ID    Name     Tag    
1     Orange   tea     
2     Pear     light   开发者_如何学JAVA 
3     Apple    tea
4     Juice    tea
5     Cocoa    baseball
6     Camera   baseball

What I want to do is for rows that have duplicate TAGS, I want to update the name of FIRST occurence with the LATEST occurence.

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

How would I do that using MySQL with PHP? Or maybe possible to just do it inside MySQL?

Thanks!


For the UPDATE query, we need to get the min and max ID's for each tag, only if there are duplicate rows:

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;

For the DELETE query, we delete all rows that are not the first ID's of its tag group:

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;
0

精彩评论

暂无评论...
验证码 换一张
取 消