剑破冰山笔记之第三章 探索Merge方法

merge的使用

  1. 业务上用t1表去更新t2表,匹配的更新,不匹配的插入
	drop table t1;
	create table t1(name varchar2(20),money number);
	insert into t1 values('A',10);
	insert into t1 values('B',10);
	drop table t2;
	create table t2 (name varchar2(20),money number);
	insert into t2 values('A',30);
	insert into t2 values('C',20);
	commit;
  1. 下面的t2表被更新,只有A匹配,A将被更新为40,C将插入到t2
	merge into t2
	using t1 on(t1.name=t2.name)
	when matched then
	update set t2.money=t1.money+t2.money--没有分号
	when not matched then
	insert values(t1.name,t1.money);--没有表名


	rollback;
	set autot on
	/

Plan hash value: 2414655244

-----------------------------------------------------------------------------
| Id  | Operation            | Name | Rows  | Bytes | Cost (%CPU)| Time     |
-----------------------------------------------------------------------------
|   0 | MERGE STATEMENT      |      |     2 |   152 |     5  (20)| 00:00:01 |
|   1 |  MERGE               | T2   |       |       |            |          |
|   2 |   VIEW               |      |       |       |            |          |
|*  3 |    HASH JOIN OUTER   |      |     2 |   124 |     5  (20)| 00:00:01 |  //可以看出是用外连接去匹配
|   4 |     TABLE ACCESS FULL| T1   |     2 |    50 |     2   (0)| 00:00:01 |
|   5 |     TABLE ACCESS FULL| T2   |     3 |   111 |     2   (0)| 00:00:01 |
-----------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   3 - access("T1"."NAME"="T2"."NAME"(+))

  1. 加条件的merge语句的用发 比较下面两者的区别,可以看出merge的过程是dml过程
	merge into t2
	using t1 on(t1.name=t2.name)
	when matched then
	update set t2.money=t1.money+t2.money  //没有分号
	when not matched then
	insert values(t1.name,t1.money) where t1.name='A'
	/
	SQL> select * from t2;
	
	NAME                      MONEY
	-------------------- ----------
	A                            40
	C                            20
  1. 加条件的merge语句的用法
	merge into t2
	using t1 on(t1.name=t2.name)
	when matched then
	update set t2.money=t1.money+t2.money  //没有分号
	when not matched then
	insert values(t1.name,t1.money) where t1.name='B'
	
	SQL> SELECT * FROM T2;
	
	NAME                      MONEY
	-------------------- ----------
	A                            40
	C                            20
	B                            10
  1. merge+rowid方式
	merge into test using
	(
	with t as
	(select 1 id,(select name from test where id=2) name from dual
	union
	 select 2,(select name from test where id=1) name from dual
	)
	select test.id,test.rowid as rn ,t.name from test,t
	where test.id=t.id)n
	on(test.rowid=n.rn)
	when matched then
	update set test.name=n.name
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值