简体   繁体   中英

Update field1 when field2 is duplicated

I would like to update latitude and longitude location from different records when their site_id is the same.

For example if

ID | SiteID | Latitude | Longitude
1      5      74.4545   -35.5466
2      6      74.4545   -35.5466
3      5      75.4584   -45.5966
4      6      79.6545   -36.5496

I would like Records 3 and all the others that match SiteID 5 to take the Latitude and Longitude of Record 1. Similarly Records 2 and 4

How can I do this in mysql.

You need to first find the correct values and then do the update. The correct values are:

select t.*
from t join 
     (select siteId, min(id) as minId
      from t
      group by siteId
     ) ts
     t.id = minId

The problem now is that you cannot update and reference the same table in a query. So, put this in a temporary table, say master .

These are the master records. You can do the update as:

update t
    join master
    on t.id = master.id
    set t.latitude = master.latitude,
        t.longitude = master.longitude

I will user site_table for the name of your table.

UPDATE site_table TARG, site_table VALDATA
SET TARG.Latitude = VALDATA.Latitude, TARG.Longitude = VALDATA.Longitude

WHERE TARG.SiteId = VALDATA.SiteId
  AND VALDATA.id = (SELECT min(MINREC.id) FROM site_table MINREC
                    WHERE MINREC.SiteId = TARG.SiteId)

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