2016-11-21 91 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