oracle 中merage Into的使用

在正式开发中,例如数据汇总,有两张表a表(子表)和b表(总表),需求,如果b表中有和a表进行关联的数据就更新相应的次数,如果b表中没有关联数据,就将a表中的数据插入到b表中;一般做法是先去b表中拿a表相应的字段去查询,如果查询到数据就执行update  sql语句,否则就执行insert sql语句;但是当数据量特别大的时候可能会出现性能问题;但是oracle提供了一个marge into 方法,该方法是判断是否有符合条件的语句,如果有就进行更新语句,否则就进行数据的插入;

marge into语法:

  1. MERGE INTO  [your table-name] [rename your table here]  
  2.   
  3. USING  ( [write your query here] )[rename your query-sql and using just like a table]  
  4.   
  5. ON  ([conditional expression here] AND [...]...)  
  6.   
  7. WHEN MATHED THEN [here you can execute some update sql or something else ]  
  8.   
  9. WHEN NOT MATHED THEN [execute something else here ! ]  
多表:例:(栗子可能举的不太合理)

情景,例如a表,b表(a表的日志表),首先进行判断b日志表中是否有a表的日志,如果没有a表的日志就插入a表的日志,否则就更新日志的提交时间,sql如下:

a表字段 id  name sex

b表字段logid id name sex

merge into   al using(select * from b where id='1') s on(l.id=s.id)
when matched then
  update set  name='质量'
when not matched then
  insert values ('1', '旺财', '男');
commit;


踩过的雷1 :

使用merge的时候,在进行数据更新的时候,on中的判断条件是不可以更新的;



单表操作:例:

情景,对于单表操作时,例如对一个表中的数据进行判断,如果表中含有指定数据,就更新,否则就插入一条新的数据

例 a表字段 id name sex count

merge into a using(select  '1'  id from dual) c on(a.id=c.id)
when matched then
  update  set count=100 where id='1'
when not matched then
 insert
values (sys_guid(),  '旺财', '女', 1, '10'));
commit;


踩过的雷2:开始的时候using中不是用的临时表,而是写的select id from a where id='2'的时候,发现,当using中查到数据时是可以更新的,但是using中查不到数据,数据无法插入,然后找了一些资料发现,merge into 语句,在useing()括号中的sql语句如果查询不到数据,是既不执行update语句也不执行insert语句的;所以在使用merge into时,要确保useing后面的sql语句可以查询到结果;


猜你喜欢

转载自blog.csdn.net/qq_34125349/article/details/77995812