MERGE是一种DML语句(数据操作语言)。
也称为 UPSERT(更新-插入)。
它尝试根据您定义的条件将源(表/视图/查询)与目标(表/可更新视图)匹配,然后根据匹配结果向目标表中插入/更新/删除行。
合并 (Transact-SQL) https://msdn.microsoft.com/en-us/library/bb510625.aspx
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 |
+---+----+
合并连接是一种连接算法(例如 HASH JOIN 或 NESTED LOOPS)。
它首先根据连接条件对两个数据集进行排序(可能由于存在索引而已排序),然后遍历排序后的数据集并查找匹配项。
create table t1 (i int)
create table t2 (i int)
select * from t1 join t2 on t1.i = t2.i option (merge join)
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 树,按主键排序。
了解合并连接 https://technet.microsoft.com/en-us/library/ms190967(v=sql.105).aspx