插入表的空列中以从联接中获取值

时间:2018-07-27 08:19:20

标签: sql join amazon-redshift sql-insert

我有这两个表:

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

我也尝试过左联接,得到相同的结果。我该怎么解决?

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:1)

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