【问题标题】:Update table based on self table lookup in redshift在 redshift 中基于自表查找更新表
【发布时间】:2017-10-16 12:05:49
【问题描述】:

我有下表,

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

但是当我尝试使用 redshift 时,它给了我以下错误:

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

如何在 redshift 中做到这一点?

【问题讨论】:

  • 不重复,我说的是同一张桌子,不是不同的桌子
  • 不要postgresql标记Redshift问题。尽管它们有一些共同的根源,但它们是非常不同的数据库。您的查询在 Postgres 中运行良好。
  • @a_horse_with_no_name 它在红移中不起作用。
  • 该问题向您展示了如何在 update 命令中join 表的语法,这正是您正在做的。只需使用该语法将您的表与自身连接起来。这就是为什么它是重复的。

标签: sql amazon-redshift


【解决方案1】:

这有点难看,但您确实必须使用自联接编写子查询,然后才能从中更新表:

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;

正如 cmets 中所说,这是从表语法进行更通用更新的特殊情况

【讨论】:

    【解决方案2】:

    使用子查询进行自连接:

    试试这个:

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

    【讨论】:

      猜你喜欢
      • 2015-11-21
      • 2017-06-26
      • 1970-01-01
      • 1970-01-01
      • 2015-08-11
      • 2013-06-12
      • 2012-07-04
      • 2022-11-27
      相关资源
      最近更新 更多