/*Merge into 详细介绍
MERGE语句是Oraclei新增的语法用来合并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 tablename] [rename your table here]
USING ( [write your query here] )[rename your querysql 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应用》中的表为例在创建另两个表fzq和fzq
*/
全部男生记录
create table fzq as select * from fzq where sex=;
全部女生记录
create table fzq as select * from fzq where sex=;
/*涉及到两个表关联的例子*/
更新表fzq使得id相同的记录中chengji字段+并且更新name字段
如果id不相同则插入到表fzq中
将fzq表中男生记录的成绩+女生插入到表fzq中
merge into fzq aa fzq表是需要更新的表
using fzq bb 关联表
on (aaid=bbid) 关联条件
when matched then 匹配关联条件作更新处理
update set
aachengji=bbchengji+
aaname=bbname 此处只是说明可以同时更新多个字段
when not matched then 不匹配关联条件作插入处理如果只是作更新下面的语句可以省略
insert values( bbid bbname bbsexbbkechengbbchengji);
可以自行查询fzq表
/*涉及到多个表关联的例子我们以三个表为例只是作更新处理不做插入处理当然也可以只做插入处理*/
将fzq表中女生记录的成绩+没有直接去sex字段而是fzq和fzq关联
merge into fzq aa fzq表是需要更新的表
using (select fzqidfzqchengji
from fzq join fzq
on fzqid=fzqid) bb 数据集
on (aaid=bbid) 关联条件
when matched then 匹配关联条件作更新处理
update set
aachengji=bbchengji+
可以自行查询fzq表
/*不能做的事情*/
merge into fzq aa
using fzq bb
on (aaid=bbid)
when matched then
update set
aaid=bbid+
/*系统提示
ORA: Columns referenced in the ON Clause cannot be updated: AAID
我们不能更新on (aaid=bbid)关联条件中的字段*/
update fzq
set id=(select id+ from fzq where fzqid=fzqid)
where id in
(select id from fzq)
使用update就可以更新