合并和合并在SQL Server中是否相同?

时间:2016-11-21 06:16:36

标签: sql sql-server-2008 sql-merge

Merge和SQL Server中的合并连接有什么区别?

1 个答案:

答案 0 :(得分:8)

MERGE 是DML语句(数据操作语言) 也称为UPSERT(更新插入) 它尝试根据您定义的条件将源(表/视图/查询)与目标(表/可更新视图)进行匹配,然后根据匹配结果将行插入/更新/删除到目标表的/中/。登记/> 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或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)

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-Tree,按主键排序。

enter image description here

Understanding Merge Joins