基于redshift中的自表查找更新表

时间:2017-10-16 12:05:50

标签: sql amazon-redshift

我有下表,

id   email   mgr_email   mgr_id
-------------------------------
1    email1   email2    
2    email2   email3
3    email3   email4

我想通过将mgr_email与电子邮件匹配来填充id列中的列mgr_id,如下所示:

id   email   mgr_email   mgr_id
-------------------------------
1    email1   email2      2
2    email2   email3      3
3    email3   email4      

以下查询在postgres中获取了所需的结果:

update mytable t1 set mgr_id=t2.id from mytable t2 where t1.mgr_email=t2.email

但是当我尝试红移时它会给我以下错误:

ERROR:  syntax error at or near "t1"
LINE 1: update mytable t1 set mgr_id=t2.id from mytable t2 where t1.mg...
                       ^

我如何在redshift中执行此操作?

2 个答案:

答案 0 :(得分:2)

它有点难看,但你真的必须用自连接编写子查询,然后才从中更新表:

update mytable
set mgr_id=t.id
from (
    select t1.email,t2.id
    from mytable t1 
    join mytable t2
    on t1.mgr_email=t2.email
) t
where mytable.email=t1.email;

如评论中所述,它是表语法

中更通用更新的特例

答案 1 :(得分:0)

使用子查询进行自我联接:

尝试一下:

update mytable 
    set mgr_id=t2.id 
    from (select id, email from mytable) t2 
    where mytable.mgr_email=t2.email