DB2,尝试在同一事务中插入新记录并删除旧记录

问题描述 投票:1回答:1

假设我有一个像这样的表,如TABLE1:

|---------------------|------------------|
|  Field Type         |         ID       |
|---------------------|------------------|
|          1          |         342      |
|---------------------|------------------|
|          2          |         343      |
|---------------------|------------------|
|          3          |         344      |
|---------------------|------------------|

还有一个临时表,如TABLE2:

|---------------------|------------------|
|  Field Type         |         ID       |
|---------------------|------------------|
|          1          |         342      |
|---------------------|------------------|
|          2          |         3455     |
|---------------------|------------------|
|          3          |         344      |
|---------------------|------------------|

我希望表1具有与表2相同的数据。因此,基本上我想更新字段类型为2的记录。理想情况下,我想从表1中删除字段类型为2的记录,并从表2中插入字段类型2的记录。

我不想删除整个表,而只是将其替换为表2的信息,我不想触摸两个表中具有相同信息的记录。我只希望删除表1中与表2不同的记录,并用表2中与该特定字段类型有关的信息替换它。

我仍然尝试插入新记录,然后返回并像这样删除:

          DELETE FROM (
  SELECT FIELD_TYPE, ID FROM TABLE1
    WHERE EXISTS (select * from TABLE2 WHERE TABLE2 .FIELD_TYPE = TABLE1 .FIELD_TYPE AND TABLE2.ID != TABLE1.ID)
 );

但是它给了我一些性能问题。我想知道是否可以通过一次交易来做到这一点。

感谢您的帮助,在此先谢谢您!

sql join db2 sql-update sql-delete
1个回答
0
投票

对于您的数据集,应执行update查询:

update table1
set id = (select id from table2 t2 where t2.field_type = table1.field_type)

您可以通过过滤仅需要更新的记录来更加具体:

update table1
set id = (select id from table2 t2 where t2.field_type = table1.field_type)
where id <> (select id from table2 t2 where t2.field_type = table1.field_type)

取决于您的DB2供应商,您还可以使用merge语法:

merge into table1 t1
using table2 t2
on (t1.field_type = t2.field_type and t1.id <> t2.id)
when matched then update set id = t2.id
© www.soinside.com 2019 - 2024. All rights reserved.