SQL中Merge用法详解 |
MERGE语句是SQL语句的一种 。在SQL Server、Oracle数据库中可用,MySQL、PostgreSQL中不可用 。MERGE是Oracle9i新增的语法,用来合并UPDATE和INSERT语句 。通过MERGE语句,根据一张表(原数据表,source table)或子查询的连接条件对另外一张(目标表,target table)表进行查询,连接条件匹配上的进行UPDATE,无法匹配的执行INSERT 。这个语法仅需要一次全表扫描就完成了全部工作,执行效率要高于INSERT+UPDATE 。 merge主要用于两表之间的关联操作 oracle中 merge: 从oracle 9i开始支持merge用法,10g有了完善 create table a (id_ integer,count_ integer); insert into a values(1,3); insert into a values(3,6); create table b (id_ integer,count_ integer); insert into b values(1,7); insert into b values(2,4); MERGE INTO a USING b ON (a.id_ = b.id_) WHEN MATCHED THEN UPDATE SET count_ = b.count_+a.count_ /* 注意指名count_属于的表 */ WHEN NOT MATCHED THEN INSERT VALUES (b.id_,b.count_); commit; select * from a; 结果: id_ count_ SQL Server 2008开始支持merge: 有两张结构一致的表:test1,test2 create table test1 (id int,name varchar(20)) go create table test2 (id int,name varchar(20)) go insert into test1(id,name) values(1,boyi55),(2,51cto),(3,bbs),(4,fengjicai),(5,alis) insert into test2(id,name) values(1,boyi),(2,51cto) 将test1同步到test2中,没有的数据进行插入,已有数据进行更新 merge test2 t --要更新的目标表 using test1 s --源表 on t.id=s.id --更新条件(即主键) when matched --如果主键匹配,更新 then update set t.name=s.name when not matched then insert values(id,name);--目标主未知主键,插入 。此语句必须以分号结束 运行以下查询查看更新结果 select a.id,a.name as name_1,b.name as name_2 from test1 as a,test2 as b where a.id=b.id id name_1 name_2 |