如何通过在mysql中连接两个表来更新

时间:2013-07-10 11:42:52

标签: mysql

我有3张桌子

  1. iata_en表3列(city_name,country_name,iata_code)
  2. d_cities表3列(city_name,country_id,iata_code)
  3. d_country表2列(country_id,country_name)
  4. 我想将iata_code列从表iata_en复制到d_citites表,其中(iata_en.cityname = d_cities.cityname)和iata_en.countryname = d_cities.country_name)

    • 所以我加入d_cities和d_country用外键来获取 COUNTRY_NAME。

    我写了这段代码,但它不起作用

    UPDATE d_cities
            SET iata_code=iata_en.iata_code
            FROM iata_en,d_cities as ci 
            INNER JOIN d_country as co
            ON ci.CountryID=co.CountryID
            WHERE iata_en.city_name=ci.city
            AND iata_en.country_name=co.country
    

2 个答案:

答案 0 :(得分:2)

所有表引用都必须在UPDATE子句中指定,即使您实际上没有更新它们。

UPDATE
    d_cities
    JOIN d_country USING (CountryID)
    JOIN iata_en ON (
        city_name = city
        AND country_name = country
    )
SET
    d_cities.iata_code = iata_en.iata_code

答案 1 :(得分:0)

尝试此查询:

 UPDATE D_CITIES CITIES
JOIN D_COUNTRY COUNTRY ON COUNTRY.COUNTRY_ID = CITIES.COUNTRY_ID
JOIN  IATA_EN IATA ON IATA.CITY_NAME = CITIES.CITY_NAME
SET CITIES.IATA_CODE = IATA.IATA_CODE;