给定一条数据,若数据库中有则更新该数据,没有则新增一条数据。使用merge into实现

1.merge into 的语法

MERGE INTO table_name alias1
USING (table | view | sub_query) alias2
ON (join condition)
WHEN MATCHED THEN
  UPDATE table_name SET col1 = col_val1, col2 = col2_val
WHEN NOT MATCHED THEN
  INSERT (column_list) VALUES (column_values);

 

通过MERGE语句,根据一张表或子查询的连接条件对另外一张表进行查询

条件匹配的进行UPDATE,无法匹配的执行INSERT。
这个语法仅需要一次全表扫描就完成了全部工作,执行效率要高于INSERT+UPDATE。

举例:

需求:判断表中是否存在ID为666的数据,如果存在更新名字为Lily,如果不存在,插入一条Lily的数据。

merge into student a
using (select '666' as id from dual) s
on (a.id = s.id)
when matched then
  update set a.name = 'Lily'
when not matched then
  insert (id, name, class) values ('666', 'Lily', '1603');

需要注意的地方(一些坑):

1.如果using中的语句查询不出来数据,是不会执行insert方法的,因为这个语法是根据using 中的查询数据进行判断                           例如这个语句是不会进行insert的

merge into student a
using (select id  from student where id = '666') s
on (a.id = s.id )
when matched then
  update set a.name = 'Lily'
when not matched then
  insert (id, name, class) values ('666', 'Lily', '1603');

2. on 中的矫健要准确的过滤,不然可能会执行全表更新

    如下这条语句会使得所有的student_name都改为Lily

merge into student a
using (select count(1) count, id  from student group by id ) s
on (a.id = s.id and count> 0)
when matched then
  update set a.name = 'Lily'
when not matched then
  insert (id, name, class) values ('666', 'Lily', '1603')

   或者这种,同上

merge into student a
using (select  id  from student where id='666') s
on (1>0)
when matched then
  update set a.name = 'Lily'
when not matched then
  insert (id, name, class) values ('666', 'Lily', '1603')

3.on中的条件和update中set的字段不能是同一个字段,否则会报错

     下例中 on的条件和update中set的字段同为id,会导致报错

merge into student a
using (select '666' as id from dual) s
on (a.id = s.id)
when matched then
  update set a.id = '666'
when not matched then
  insert (id, name, class) values ('7', 'Lily', '1603');

4.using 中查询出来的数据不能有重复,否则会报错

发布了41 篇原创文章 · 获赞 1 · 访问量 1854

猜你喜欢

转载自blog.csdn.net/qq_38087131/article/details/105582231