Mysql:如何将表字段更新为从另一个表获取的值

时间:2019-05-21 06:15:10

标签: mysql sql

我有两个表,我们将其命名为 A和B ,并具有以下字段:

表A

| ID | COUNTRY_CODE | COUNTRY_NAME | FIRST_NAME | LAST_NAME |

表B

| ID | COUNTRY_CODE | COUNTRY_NAME |

现在,我需要从表A 中更新 country_code 字段,该字段的值将从表B 中获取。

伪代码是这样的:

for all rows in Table A :
  set A.country_code = (select B.country_code from B where B.country_name = A.country_name

2 个答案:

答案 0 :(得分:1)

JOIN使用更新

update TableA A
inner join tableB B on B.country_name = A.country_name
set A.country_code=B.Country_code

答案 1 :(得分:0)

不需要join,只需尝试如下所示的sql:

update TableA set country_code = B.country_code from TableB B where A.country_name = B.country_name