sql - 如何在有条件的情况下将记录从另一个表插入到一个表中
问题描述
我正在开发一个包含Insert into
语句的程序,我想为其添加一些条件。
假设TARGET_TABLE
有 2 个主键列A, B
和 1 个变量 C(其值为“NO”或“YES”)。
对于SOURCE_TABLE
.
- 如果 中的记录
SOURCE_TABLE
不存在TARGET_TABLE
则插入 - 如果主键列中已经存在
TARGET_TABLE
具有相同值且变量 C = "NO" 的记录,则仅当新记录具有变量 C = "YES"时才更新记录 - 如果主键列中已经存在
TARGET_TABLE
具有相同值的记录,并且变量 C =“YES”,则不要插入
你有什么想法吗?我尝试使用“不存在的地方”,然后尝试使用“Case when”,但我不知道如何在同一个程序中混合这 3 个案例......
解决方案
我认为这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
推荐阅读
- android - Android可以访问android中任何应用程序的应用内购买吗
- html - How to remove space between content and left border in p tag?
- ruby-on-rails - 优化/缩短此代码片段的方法
- html - 下标和常规文本 HTML 之间的水平空格
- sql - PL/SQL 获取多于请求的行数
- firebase - 如何将 Firebase 集合的每个文档设为 ListTile?
- python - 使用涉及其他 2 列的条件填充 pandas 列中的值
- javascript - 父元素悬停时如何触发lottie悬停?
- php - 为什么在 PHP 的 for 循环中加法不起作用而不是递增运算符?
- php - SQL order by total of value by rows