简体   繁体   English

复制field2时更新field1

[英]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. 当它们的site_id相同时,我想从不同的记录中更新纬度和经度位置。

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 我希望记录3和所有与SiteID 5匹配的其他记录都采用记录1的纬度和经度。类似地,记录2和4

How can I do this in mysql. 我该如何在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 . 因此,将其放在一个临时表中, 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. 我将使用site_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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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