首页 > 解决方案 > 如何在有条件的情况下将记录从另一个表插入到一个表中

问题描述

我正在开发一个包含Insert into语句的程序,我想为其添加一些条件。

假设TARGET_TABLE有 2 个主键列A, B和 1 个变量 C(其值为“NO”或“YES”)。

对于SOURCE_TABLE.

  1. 如果 中的记录SOURCE_TABLE不存在TARGET_TABLE则插入
  2. 如果主键列中已经存在TARGET_TABLE具有相同值且变量 C = "NO" 的记录,则仅当新记录具有变量 C = "YES"时才更新记录
  3. 如果主键列中已经存在TARGET_TABLE具有相同值的记录,并且变量 C =“YES”,则不要插入

你有什么想法吗?我尝试使用“不存在的地方”,然后尝试使用“Case when”,但我不知道如何在同一个程序中混合这 3 个案例......

标签: sqloracle-sqldeveloper

解决方案


我认为这merge涵盖了所有情况(Oracle 解决方案):

merge into target_table t
using source_table s
on (t.a = s.a and t.b = s.b)
when matched then update set d = s.d, c = s.c where t.c = 'NO' and s.c = 'YES'
when not matched then insert values (s.a, s.b, s.c, s.d)

所以对于这些样本数据:

create table target_table(a, b, c, d) as (
   select 1, 2, 'NO',  100 from dual union all
   select 1, 3, 'NO',  100 from dual union all
   select 1, 4, 'NO',  100 from dual union all
   select 1, 5, 'YES', 100 from dual );

create table source_table(a, b, c, d) as (
   select 1, 1, 'NO',  200  from dual union all
   select 1, 3, 'YES', 200  from dual union all
   select 1, 4, 'NO',  200  from dual union all
   select 1, 5, 'YES', 200  from dual );

你得到:

     A          B C            D
------ ---------- --- ----------
     1          1 NO         200
     1          2 NO         100
     1          3 YES        200
     1          4 NO         100
     1          5 YES        100

小提琴手


推荐阅读