从另一个表的数据更新表

时间:2015-02-24 15:09:15

标签: sql sqlite

我有2个表:customer(customer,city_name,postal_code)和postal_codes(city_name,postal_code)。

在customers表中,postal_code条目丢失,但城市就在那里。

如何从postal_codes表更新customers表,以便在缺少postal_code的customers表中更新丢失的postal_code?

这可能是重复但我无法从类似的线程中做出任何建议。他们都使用某些表格名称的缩写,我觉得很难遵循。

试过这个,但它似乎不起作用:

UPDATE  customers
SET     postal_code = postal_codes.postal_code
FROM    postal_codes.postal_code INNER JOIN postal_codes.city_name ON customers.city_name 

1 个答案:

答案 0 :(得分:0)

据我所知,SQLite不支持update ... from join语法,但此查询应该适合您:

UPDATE customers
SET postal_code = (
  SELECT postal_codes.postal_code 
  FROM postal_codes
  WHERE postal_codes.city_name = customers.city_name 
)
WHERE EXISTS (
  SELECT *
  FROM postal_codes
  WHERE postal_codes.city_name = customers.city_name
    AND postal_codes.postal_code <> customers.postal_code
);