Search code examples
mysqlsqlsql-updatesql-insertinsert-select

mysql update rows of column in second table from column in first table where another column in first table matches column in second table


My title may be a little confusing, but this is basically what I want to do:

I have two tables:

Table 1 = Site

Columns: SiteID    SiteName    Address
           1       Germany     123 A Street
           2       Poland      234 B Street
           3       France      354 F Street
           4       England     643 C Street
           5       Russia      968 G Street

Table 2 = Site_New

Columns: SiteID    SiteName    Address
           1       Germany
           2       France
           3       Russia

I wan't to update the Address column in table 2 with the Address in table 1 where SiteName in table 2 = SiteName in table 1. As you can see there are sites in table 1 that are not in table 2, so I do not care about copying those addresses to table 2.

I was trying this code:

update Site_New set Address = (select Site.Address from Site where Site_New.SiteName=Site.SiteName)

but I was getting error code 1242: "Subquery returns more than 1 row."

Any idea on how this can be done?


Solution

  • You are better off using update/join syntax:

    update Site_New sn join
           Site s
           on sn.SiteName = s.SiteName
        set sn.Address = s.Address;
    

    However, based on your sample data, your correlated subquery should not cause such an error.

    Perhaps the join should be on SiteId rather than SiteName:

    update Site_New sn join
           Site s
           on sn.SiteId = s.SiteId
        set sn.Address = s.Address;