基于具有外键的连接更新列中的数据

时间:2015-11-06 10:55:37

标签: mysql

我有一个表有一些不正确的数据,我想纠正。例如 - 在'address_detail'表中,地址字段错误地以'null'为前缀而不是城市名称。

id  | city_id   | address
-------------------------------
7   | 1         | Mexico/Street39
8   | 2         | New York/Street40
9   | 3         | Washington/Street41
10  | 4         | Los Angeles/Street42

更正后,我希望数据如下:

address_detail table

UPDATE
    address_detail ad
SET
    ad.address = (CONCAT( SELECT name FROM city c WHERE c.id = ad.city_id, SUBSTRING( ad.address, 5 )))
WHERE
    ad.address LIKE 'null/%'

我尝试了以下脚本,但却给了我错误。

GROUP BY

1 个答案:

答案 0 :(得分:2)

UPDATE
    address_detail ad
SET
    ad.address = REPLACE(ad.address, 'null', ( SELECT name FROM city c WHERE c.id = ad.city_id))
WHERE
    ad.address LIKE 'null/%'