Merge into 详细介绍

来源:互联网 发布:微信如何打开淘宝链接 编辑:程序博客网 时间:2024/05/18 03:18


/*Merge into 详细介绍

MERGE语句是Oracle9i新增的语法,用来合并UPDATE和INSERT语句。
通过MERGE语句,根据一张表或子查询的连接条件对另外一张表进行查询,
连接条件匹配上的进行UPDATE,无法匹配的执行INSERT。
这个语法仅需要一次全表扫描就完成了全部工作,执行效率要高于INSERT+UPDATE。

*/


/*语法:


MERGE [INTO [schema .] table [t_alias]
USING [schema .] { table | view | subquery } [t_alias]
ON ( condition )
WHEN MATCHED THEN merge_update_clause
WHEN NOT MATCHED THEN merge_insert_clause;

*/


语法:


MERGE INTO [your table-name] [rename your table here]

USING ( [write your query here] )[rename your query-sql and using just like a table]

ON ([conditional expression here] AND [...]...)

WHEN MATHED THEN [here you can execute some update sql or something else ]

WHEN NOT MATHED THEN [execute something else here ! ]


/*
我们还是以《sql中的case应用》中的表为例。在创建另两个表fzq1和fzq2
*/
--全部男生记录
create table fzq1 as select * from fzq where sex=1;

--全部女生记录
create table fzq2 as select * from fzq where sex=0;

/*涉及到两个表关联的例子*/--更新表fzq1使得id相同的记录中chengji字段+1,并且更新name字段。--如果id不相同,则插入到表fzq1中.--将fzq1表中男生记录的成绩+1,女生插入到表fzq1中merge into fzq1  aa     --fzq1表是需要更新的表using fzq bb            -- 关联表on (aa.id=bb.id)        --关联条件when matched then       --匹配关联条件,作更新处理update setaa.chengji=bb.chengji+1,aa.name=bb.name         --此处只是说明可以同时更新多个字段。when not matched then    --不匹配关联条件,作插入处理。如果只是作更新,下面的语句可以省略。insert values( bb.id, bb.name, bb.sex,bb.kecheng,bb.chengji);--可以自行查询fzq1表。


/*涉及到多个表关联的例子,我们以三个表为例,只是作更新处理,不做插入处理。当然也可以只做插入处理*/--将fzq1表中女生记录的成绩+1,没有直接去sex字段。而是fzq和fzq2关联。merge into fzq1  aa     --fzq1表是需要更新的表using (select fzq.id,fzq.chengji        from fzq join fzq2       on fzq.id=fzq2.id) bb  -- 数据集on (aa.id=bb.id)        --关联条件when matched then       --匹配关联条件,作更新处理update setaa.chengji=bb.chengji+1--可以自行查询fzq1表。


/*不能做的事情*/

merge into fzq1  aa   

using fzq bb          

on (aa.id=bb.id)       

when matched then      

update set

aa.id=bb.id+1

/*系统提示:

ORA-38104: Columns referenced in the ON Clause cannot be updated: "AA"."ID"

我们不能更新on (aa.id=bb.id)关联条件中的字段*/

update fzq1

set  id=(select id+1 from fzq where fzq.id=fzq1.id)

where id in

(select id from fzq)

--使用update就可以更新,如果有更好的方法,谢谢反馈!


作者:tshfang
来源: 泥胚文章写作 http://www.nipei.com 原文地址:http://www.nipei.com/article/9855