【问题标题】:delete functionality incremental load in sql server在 sql server 中删除功能增量负载
【发布时间】:2018-07-04 10:20:53
【问题描述】:

我需要删除存在于目标表中但不存在于源表中的记录。目标表中的主键是源表中不存在的 auto_increment ID。源表和目标表都包含一组唯一键组合,可用于唯一标识任一表中的行。我应该遵循什么方法?如果我要使用多个列组合作为唯一键而不是一个主键(源中没有),我该如何删除?

 delete from dest_table
 where (uniq_key_col1,uniq_key_col2) not in (
   select dest.uniq_key_col1,dest.uniq_key_col2 
   from dest_table dest
   join source_table source
   on dest.uniq_key_col1=source.uniq_key_col1
   and dest.uniq_key_col2=source.uniq_key_col2
 )

这是它的理想外观(只是为了清楚起见,请忽略 where 子句中的错误,因为有多个列)

【问题讨论】:

标签: sql sql-server sql-server-2008


【解决方案1】:

你可以使用存在。即:

delete from dest_table
 where not exists (
   select * 
   from source_table source
   where dest_table.uniq_key_col1=source.uniq_key_col1
   and dest_table.uniq_key_col2=source.uniq_key_col2
 );

【讨论】:

  • 这似乎是使用not exists 的第一个答案,因此值得点赞。
  • @GordonLinoff 我同意 - 尽管我只落后 5 秒:P
【解决方案2】:

你可以这样做:

DELETE
FROM dbo.dest a 
WHERE NOT EXISTS (
      SELECT 1
        FROM dbo.source1 b
       WHERE a.id1 = b.ID1 and a.id2 = b.id2
      )

【讨论】:

    【解决方案3】:

    听起来你需要的不是EXISTS

    DELETE d FROM dest_table d 
    WHERE NOT EXISTS (SELECT (PUT_APPROPRIATE_COLUMNS_HERE) from source_table s 
       WHERE d.col1 = s.col
       AND d.col2 = s.col2
       ... etc for other columns
       )
    

    注意表别名,你需要它。如果您的数据可能,使用内部联接可能更合适。

    【讨论】:

    • 如在中,列出您想要在 SELECT 中的列,或者 * 如果首选
    • 如果您在用于 EXISTS 查询的选择中有列列表或 * 或任何文字(如 1 或 'x'),这有什么关系?
    • 可以 - 提问者似乎想要一个列列表,所以如果需要,我指出了在哪里列出它们。 “1”也是一个“适当的”列
    • EXISTS 查询不处理列列表,也不管返回一个简单的布尔值。
    【解决方案4】:

    你的另一个选择

    DELETE dest_table
    FROM dest_table
        LEFT JOIN source_table
            ON dest_table.uniq_key_col1 = source_table.uniq_key_col1
                AND dest_table.uniq_key_col2 = source_table.uniq_key_col2
    WHERE source_table.uniq_key_col1 IS NULL
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-19
      • 2015-03-04
      • 1970-01-01
      相关资源
      最近更新 更多