【问题标题】:Mysql - Populate data in one column based on join with three different fieldsMysql - 基于三个不同字段的连接在一列中填充数据
【发布时间】:2020-09-26 18:16:16
【问题描述】:

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

如果 House id 与 Address 表中的 house id 匹配,则填充 state 列,否则如果学校 id 匹配,否则如果 office 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

谢谢

【问题讨论】:

  • “新表”实际上是一个表?或者您希望“地址表”的预期输出类似于“新表”
  • 'SC002' 来自哪里?它不在原始数据中。

标签: mysql sql sql-update left-join inner-join


【解决方案1】:

试试这个查询:

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);

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2015-11-20
      • 1970-01-01
      • 2023-03-09
      • 2020-07-30
      • 2016-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-24
      相关资源
      最近更新 更多