mysql-基于join在一列中填充数据,其中包含三个不同的字段

tv6aics1  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(335)

我们在一个地址表中维护地址,比如说房子,学校,办公室。我想在一个新的表中得到'state'列基于以下条件。
若房屋id和地址表中的房屋id匹配,则填充状态列;若学校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

谢谢

ntjbwcob

ntjbwcob1#

你可以的 lef join 这个 new_table 三次,使用 coalesce() 优先顺序:

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 子句确保至少有一个联接成功。

deikduxw

deikduxw2#

尝试此查询:

SELECT NewTable.State FROM NewTable WHERE 
NewTable.School IN (SELECT AddressTable.AdressId FROM AddressTable) 
OR NewTable.Office IN (SELECT AddressTable.AdressId FROM AddressTable) 
OR NewTable.House IN (SELECT AddressTable.AdressId FROM AddressTable);

相关问题