简体   繁体   中英

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

Try this:

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

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 !!!

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM