2016-11-21 90 views

回答

2

MERGE是一个DML语句(数据操作语言)。
也称为UPSERT(更新 - 插入)。
它尝试根据您定义的条件将源(表/视图/查询)与目标(表/可更新视图)进行匹配,然后根据匹配结果将行插入/更新/删除到目标表的/ in /目录。
MERGE (Transact-SQL)

create table src (i int, j int); 
create table trg (i int, j int); 

insert into src values (1,1),(2,2),(3,3); 
insert into trg values (2,20),(3,30),(4,40); 

merge into trg 
using  src 
on   src.i = trg.i 
when not matched by target then insert (i,j) values (src.i,src.j) 
when not matched by source then update set trg.j = -1 
when matched then update set trg.j = trg.j + src.j 
; 

select * from trg order by i 

+---+----+ 
| i | j | 
+---+----+ 
| 1 | 1 | 
+---+----+ 
| 2 | 22 | 
+---+----+ 
| 3 | 33 | 
+---+----+ 
| 4 | -1 | 
+---+----+ 

MERGE JOIN是一个连接算法(例如HASH JOIN或嵌套的循环)。
它基于首先根据连接条件对两个数据集进行排序(可能已经根据索引存在进行排序),然后遍历排序的数据集并查找匹配。

create table t1 (i int) 
create table t2 (i int) 

select * from t1 join t2 on t1.i = t2.i option (merge join) 

enter image description here

create table t1 (i int primary key) 
create table t2 (i int primary key) 

select * from t1 join t2 on t1.i = t2.i option (merge join) 

在SQL Server主键意味着这意味着该表被存储为B树聚集索引结构中,通过主键进行排序。

enter image description here

Understanding Merge Joins

+0

能否请您为我提供一个例子 – Catwoman

+0

@Catwoman一看,在接下来的一个小时 –

+0

非常感谢@Dudu – Catwoman