【问题标题】:Insert in empty column of table obtaining values from a join插入从连接获取值的表的空列
【发布时间】:2019-01-04 07:56:44
【问题描述】:

我有这两张表:

rbi_world_holi_prov

accentcity      region_name
Madrid          Madrid
Barcelona       Cataluña
Berlin          Berlin
Sevilla         Andalucia

rbi_ip

ip                city      region_name
85.59.64.116      Berlin    <null>
195.235.205.150   Madrid    <null>
83.231.53.43      Barcelona <null>
2.136.208.188     Sevilla   <null>

我想得到这个:

ip                city      region_name
85.59.64.116      Berlin    Berlin
195.235.205.150   Madrid    Madrid
83.231.53.43      Barcelona Cataluña
2.136.208.188     Sevilla   Andalucia

通过以下查询,我得到了我想要的:

select i.city,i.ip,w.region_name 
from rbi_ip as i
inner join rbi_world_holi_prov as w
on lower(i.city) =lower(w.accentcity)

但是,如果我添加这个插入语句:

insert into rbi_ip (region_name)
select i.city,i.ip,w.region_name 
from rbi_ip as i
inner join rbi_world_holi_prov as w
on lower(i.city) =lower(w.accentcity)

我明白了:

ip                city      region_name
85.59.64.116      Berlin    <null>
195.235.205.150   Madrid    <null>
83.231.53.43      Barcelona <null>
2.136.208.188     Sevilla   <null>
<null>            <null>    Madrid
<null>            <null>    Cataluña
<null>            <null>    Berlin
<null>            <null>    Sevilla

我也尝试了左连接,得到了相同的结果。我该如何解决这个问题?

【问题讨论】:

    标签: sql join amazon-redshift sql-insert


    【解决方案1】:

    您不想在表中插入要更新的列。

    update rbi_ip
    set rbi_ip.region_name = rbi_world_holi_prov.region_name 
    from rbi_world_holi_prov
    where lower(rbi_ip.city) = lower(rbi_world_holi_prov .accentcity)
    

    【讨论】:

    • 只需编辑语句,替换 't2.'在代码的第二行中使用“w”。 (因为 'w' 后来用作表 2 的同义词)
    • 使用该查询我得到下一个错误:无效操作:关系“rbi”不存在。我尝试使用更新 rbi_ip 明确命名表,但随后我得到:无效操作:关系“rbi_ip_backup”的列“rbi”不存在
    • @dimo raichev 哈哈我无意按回车,已经编辑好了
    • @JavierLópezTomás 你能再试一次吗,编辑我的答案
    【解决方案2】:
    you can also use alias name for the table while updating data , just like i have used i here 
    
    Update i Set region_name =w.region_name
    from rbi_ip_backup as i
    inner join rbi_world_holi_prov as w
    on lower(i.city) =lower(w.accentcity)
    

    然后使用

    Select * from rbi_ip_backup
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 2018-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多