Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update only first record from duplicate entries in MySQL

Tags:

php

mysql

Problem SOLVED!

Update:

Not quite right what I need, lets do example on simple table with fields ID,NAME,COVER

I have got 100 entries with 100 names, some of the names are duplicated, but I want only update first one from duplicates.


Trying to update all the 1st rows from all the duplicates in database, really hard to do it, any idea how I can make it? Below is the code I am trying to rebuild, but this code replace every 1st one with the last one for all the duplicates.

Schema, how I want it work below

ID NAME COVER
1  Max   1
2  Max   0
3  Andy  1
4  Andy  0
5  Andy  0

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;
like image 263
user974435 Avatar asked Jan 18 '23 14:01

user974435


1 Answers

It's not clear at all what you want. Perhaps this:

UPDATE table AS t
  JOIN 
    ( SELECT MIN(ID) MinID
      FROM table
      GROUP BY Name
      HAVING COUNT(*) > 1
    ) AS m 
    ON t.ID = m.MinID
SET t.Cover = 1 ;

For this (and future) question, keep in mind, when you write a question:

1. a description of your problem, as clear as possible    --- you have that
2. data you have now (a few rows of the tables)           --- ok, nice
3. the code you have tried                 --- yeah, but better use same names
                                           --- as the data and description above
4. the error you get (if you get an error)      --- doesn't apply here
5. the result you want (the rows after the update in your case)
                                       --- so we know what you mean in case we 
                                       --- haven't understood from all the rest 
like image 157
ypercubeᵀᴹ Avatar answered Feb 08 '23 16:02

ypercubeᵀᴹ