【问题标题】:Teradata update with left join and inner join使用左连接和内连接进行 Teradata 更新
【发布时间】:2020-02-05 20:18:37
【问题描述】:

我需要将下面的示例代码从 mssql 带到 Teradata。请让我知道如何转换它。示例代码 -

Update table1
set table1.name = table3.name 
from table1 
inner join table2 
on table2.id = table1.id 
left join table3 
on table2.id = table3.id where table3.name is null

【问题讨论】:

  • 为什么table3.name is null 在where 子句中?您在update 中使用它。为什么不在set 中使用显式的null?
  • 本质上,我希望将左连接后的所有不匹配值都更新为 NULL。

标签: sql join sql-update teradata


【解决方案1】:

这很难看,但这应该可以。您可以通过使用派生表绕过 Teradata 不允许在更新中进行外部联接。

update table1
from table1,
(select <column list> from table2 left join table3 on table2.id = table3.id) t
set ...
where
table1.id = t.id
and t.name is null

【讨论】:

  • @AswinKs:如果这解决了您的问题,请考虑accepting the answer...
  • 看来我没有足够的声誉来接受答案:(
  • 我认为你应该能够接受答案(复选标记),但不能以你目前的声誉支持它。
【解决方案2】:

像提到的其他人一样,您应该检查您的NULL 条件。不过,这里还有一个选择:

Update table1
FROM (
  select table1.id, table3.name
  from table1 
  inner join table2 
  on table2.id = table1.id 
  left join table3 
  on table2.id = table3.id where table3.name is null
) src
SET table1.name = src.name
WHERE table1.id = src.id

您只需将原始源查询移动到“src”子查询中并从中进行更新。只需确保在“src”查询中每个 table1.id 值只有一行,这样就不会出现 target row updated by multiple source rows 错误。

【讨论】:

  • 我认为我们需要在 from 子句中也包含 table1,否则会给出错误代码 3993 非法使用别名
【解决方案3】:

我认为not exists处理你的逻辑更好:

Update table1
    set table1.name = null
    where not exists (select 1
                      from table2 join
                           table3 
                           on table2.id = table3.id
                      where table2.id = table1.id 
                     );

这不是完全您的查询指定的内容——当table2 中没有匹配项时,这将更新table1.name。如果这是一个问题,您可以这样做:

update table1
    set table1.name = null
    where exists (select 1
                  from table2
                  where table2.id = table3.id
                 ) and
          not exists (select 1
                      from table2 join
                           table3 
                           on table2.id = table3.id
                      where table2.id = table1.id 
                     );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-15
    • 2015-03-04
    • 2018-07-31
    • 1970-01-01
    相关资源
    最近更新 更多