SQL Update表1使用表2 UPDATE FROM SELECT

时间:2014-09-10 11:53:15

标签: mysql sql-update

我正在尝试更新table1的country_id,因此我可以删除列iso_2_codeCountry,因为这些数据在数据库中是多余的,并且已存储在table2中

表1 - oc_ip_geo_table

=================================================================================================
|   ID  |    StartRange     |   EndRange        |   iso_2_code  |   Country     |   country_id  |
=================================================================================================
|  1    |    1.0.1.0        |   1.0.3.255       |       CN      |   China       |       0       |
|  2    |    1.0.4.0        |   1.0.7.255       |       AU      |   Australia   |       0       |
|  3    |    1.0.8.0        |   1.0.15.255      |       CN      |   China       |       0       |
|  4    |    1.0.16.0       |   1.0.31.255      |       JP      |   Japan       |       0       |
|  ...  |    ...            |   ...             |       ...     |   ...         |       ...     |
| 87035 |    223.255.255.0  |   223.255.255.255 |       AU      |   Australia   |       0       |
-------------------------------------------------------------------------------------------------

表2 - oc_country

=================================================================================
|   country_id      |   name            |   iso_code_2  |   *   |   *   |   *   |
=================================================================================
|       1           |   Afghanistan     |       AF      |   *   |   *   |   *   |
|       2           |   Albania         |       AL      |   *   |   *   |   *   |
|       3           |   Algeria         |       DZ      |   *   |   *   |   *   |
|       ...         |   ...             |       ...     |   ... |   ... |   ... |
|       251         |   Canary Islands  |       IC      |   *   |   *   |   *   |
---------------------------------------------------------------------------------

搜索到谷歌搜索结果后,我发现我的查询应该是这样的。但似乎没有用。

UPDATE oc_ip_geo_table
SET oc_ip_geo_table.country_id = oc_country.country_id
FROM oc_ip_geo_table
INNER JOIN oc_country
ON oc_ip_geo_table.iso_2_code = oc_country.iso_code_2

任何人都可以帮我解决正确的查询

2 个答案:

答案 0 :(得分:0)

我不确定..但我认为您必须在SET

之后删除oc_ip_geo_table
UPDATE oc_ip_geo_table
SET country_id = occ.country_id
FROM oc_ip_geo_table opi
INNER JOIN oc_country occ
ON opi.iso_2_code = occ.iso_code_2

答案 1 :(得分:0)

好吧看起来我在这里发布的那个之前尝试的查询几乎是正确的但是改变了一点解决了它

UPDATE oc_ip_geo_table AS t1
SET t1.country_id = 
    ( SELECT t2.country_id 
      FROM oc_country AS t2 
      WHERE t2.iso_code_2 = t1.iso_2_code

    )

已更改为

UPDATE oc_ip_geo_table AS t1
SET t1.country_id = 
    ( SELECT t2.country_id 
      FROM oc_country AS t2 
      WHERE t1.iso_2_code = t2.iso_code_2

    )