首页 > 解决方案 > Mysql - 基于三个不同字段的连接填充一列中的数据

问题描述

我们在一个地址表中维护说房子、学校、办公室的地址。我想根据以下条件在新表中获取“状态”列。

如果 House id 与 Address 表中的 house id 匹配,则填充 state 列,否则如果学校 id 匹配,否则如果办公室 id 匹配。

地址表:

Address Id  State City
SC001       Iowa  Cedar
HO001       Iowa  Cedar
HO002       Ohio  Columbus
OF002       Ohio  Columbus

新表

School Office   House   State
SC001    OF001    HO001   Iowa
SC002    OF002    HO002   Ohio

谢谢

标签: mysqlsqlsql-updateleft-joininner-join

解决方案


您可以三次,并lef join用于优先级:new_tablecoalesce()

update address_table a
left join new_table n1 on n1.house_id  = a.addres_id
left join new_table n2 on n2.school_id = a.addres_id
left join new_table n2 on n3.office_id = a.addres_id
set a.state = coalesce(n1.state, n2.state, n3.state)
where coalesce(n1.house_id, n2.school_id, n3.office_id) is not null

where子句确保至少有一个连接成功。


推荐阅读