一、用途
可以同时从1个或者多个源头对表进行更新或者插入,删除 经常用于操作大量的数据,即对于大批量的数据更新、插入时效率极高。
二、语法
merge into table_name alias1 --需要操作的表 可以用别名
using (table|view|sub_query) alias2 --数据来源 可以是表、视图、子查询
on (join condition) --关联条件
when matched then --当关联条件成立时 更新,删除,插入的where部分为可选
update table_name set col1=colvalue where……
--更新
delete from table_name where col2=colvalue where……--删除 可以只更新 删除 也可以只删除不更新
when not matched then --当关联条件不成立时 0racle 10 以后 此处可以不用
insert (col3) values (col3values) where……;
注意
1、只会操作“操作表”,源表不会有任何变化
2、不一定要把update,delete,insert 操作都写全,可以根据实际情况
三、实例演示
有三张表 部门表dept (部门id,部门名称),工资表salary(员工id,工资),
员工表 employess(员工id,姓名,职位,部门,工作年限)
具体数据如下:
部门表dept:
工资表salary:
员工表employess:
可知工资表中还没有诸葛亮 的信息,现在要求我们将工资表中删除马畜的工资信息,并将部门名称是销售部职位是员工的工资提升20%(注意这里我们并不知道信息技术部的部门代码,还是需要关联部门信息表),插入工号1012,工资为6000。
如果没有merge into 我们需要分开执行三个sql,分开写的sql如下:
--删除
delete from salary t
where exists (select 1
from employess a
where a.e_id = t.e_id
and a.e_name = '张飞')
--更新
update salary t
set t.e_sal = t.e_id * 1.2
where exists (select 1
from employess a, dept b
where a.e_id = t.e_id
and a.d_id = b.dept_id
and a.e_position = '员工'
and b.d_name = '销售部')
--插入
insert into salary values('1012',6000);
但是有了merge into,我们可以一个sql搞定:
merge into salary t
using (select t1.e_id,
t1.e_name,
t1.e_position,
t2.dept_id,
t2.d_name
from employess t1, dept t2
where t1.d_id = t2.dept_id) e
on (t.e_id = e.e_id)
when matched then
update
set t.e_sal = t.e_sal * 1.2
where e.e_position = '员工'
and e.d_name = '销售部'
delete where (e.e_name='张飞')
when not matched
then
insert (e_id, e_sal) values ('1012', 6000);
执行结果
‘’
可知 工资表中 工号1011的 张飞信息已被删除
并把1010的工资加了300同时 增加了1012的工资信息