ChongWang87
ChongWang87

Reputation: 39

Update columns to min value from a group

i have database like this

 uniqueid |     name    | newid | sirname
----------+-------------+-------+---------
     A1   |     Adam    |  NULL |  Danny 
     A2   |  Adam (Lee) |  NULL |  Danny 
     A5   |  Adam (Koh) |  NULL |  Danny
     B4   |     Bruce   |  NULL |    CK
     B6   |  Bruce (Lee)|  NULL |    CK 

How can I update all the newid to min(unique id) from group by sirname

The result i want:

 uniqueid |     name    | newid | sirname
----------+-------------+-------+---------
    A1    |     Adam    |   A1  |  Danny
    A2    |  Adam (Lee) |   A1  |  Danny
    A5    |  Adam (Koh) |   A1  |  Danny
    B4    |     Bruce   |   B4  |   CK
    B6    | Bruce (Lee) |   B4  |   CK

Upvotes: 0

Views: 169

Answers (3)

RolandoMySQLDBA
RolandoMySQLDBA

Reputation: 44363

Try this UPDATE JOIN

UPDATE
    (
        SELECT sirname,MIN(uniqueid) min_uniqueid
        FROM mytable GROUP BY sirname
    ) A
    INNER JOIN mytable B
    USING (sirname)
SET
    B.newid = A.min_uniqueid
;

For this query to work very fast, make sure you have a compound index on sirname and uniqueid.

If you do not have such an index, then run this beforehand:

ALTER TABLE mytable ADD INDEX sirname_uniqueid_ndx (sirname,uniqueid);

Give it a Try !!!

Upvotes: 0

James
James

Reputation: 3805

If BD.'s doesn't work, try:

Update tableName As a 
  Set newid = 
    (Select uniqueid 
      From tableName As b 
      Where b.sirname = a.sirname 
      Order By uniqueid 
      Limit 1)

Upvotes: -1

BD.
BD.

Reputation: 890

Try this:

UPDATE table a 
SET    new_id = (SELECT MIN(unique_id) 
                 FROM   table b 
                 WHERE  b.sirname = a.sirname)

Upvotes: 2

Related Questions