【问题标题】:Query to delete record when no matching in delta table当增量表中没有匹配时查询删除记录
【发布时间】:2022-01-15 06:00:15
【问题描述】:

请帮助编写一个更好的删除查询。 DB2 没有“与源不匹配”的合并。 需要从 ID 的源文件中删除没有匹配代码的行,并且只需要删除源文件中存在的 ID 的行。

delete from target
   where ID in ( select ID from source)
         and 
      ID concat Code NOT in ( Select S.ID concat S.Code from source S)

样本数据

target             source 
ID   code         ID   code         
1    ABC          1     ABC     
1    DEF          1     DEF
1    IJK
2    ABC
2    XYZ

值 ID=1 & code=IJK 的行需要从目标中删除

【问题讨论】:

  • 请添加几行样本数据和预期的结果。看起来不难做,但没有例子很难说。
  • 添加样本数据和预期结果

标签: sql db2 sql-delete ibm-midrange


【解决方案1】:

你可以这样做:

delete from target
where (id, code) in (
  select t.id, t.code
  from target t
  left join source s on (s.id, s.code) = (t.id, t.code)
  where s.id is null and t.id in (select id from source)
);

结果:

 ID  CODE 
 --- ---- 
 1   ABC  
 1   DEF  
 2   ABC  
 2   XYZ  

请参阅db<>fiddle 的运行示例。

我确信可以使用DELETE & JOIN 或使用EXISTS 而不是IN 来压缩语法,但是这个例子应该是一个很好的解决方案。

【讨论】:

    猜你喜欢
    • 2013-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-17
    • 1970-01-01
    • 1970-01-01
    • 2015-11-28
    • 1970-01-01
    相关资源
    最近更新 更多