温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

merge into基本用法

发布时间:2020-08-04 15:47:15 来源:ITPUB博客 阅读:253 作者:llnnmc 栏目:关系型数据库

由于merge into平时很少用,但这次用到它来给记录做插入更新,于是简单记下最基本的用法。这里的例子就是给一个表中符合条件的数据做个值计数的更新,如果找到符合ID条件的记录,那么就将其值字段加1,否则就插入这条新的记录,并初始化值。

创建测试表并插入数据:
create table test1(id number, val number);
insert into test1 values(101, 1);
insert into test1 values(102, 1);
commit;
select * from test1;

        ID        VAL
---------- ----------
       101          1
       102          1

做merge into操作,新的一条数据被插入:
merge into test1 t1
using (select count(*) cnt from test1 where id = 103) t2 on (cnt <> 0)
when matched then
  update set val = val + 1 where id = 103
when not matched then
  insert values(103, 1);
commit;
select * from test1;

        ID        VAL
---------- ----------
       101          1
       102          1
       103          1

再执行一个merge into后,数据被更新:

        ID        VAL
---------- ----------
       101          1
       102          1
       103          2


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI