在线捏脸网站需要多少钱,wordpress付费附件下载,洛阳网站设计开发,舆情报告单文章目录 merge into使用场景merge into语法测试表普通模式 merge使用注意点 merge into
MERGE 是 Oracle9i 新增的语法#xff0c;根据源表对目标表进行匹配查询#xff0c;匹配成功时更新#xff0c;不成功时插入 比单独的 update insert 的方式效率要更高#xff0c;尤… 文章目录 merge into使用场景merge into语法测试表普通模式 merge使用注意点 merge into
MERGE 是 Oracle9i 新增的语法根据源表对目标表进行匹配查询匹配成功时更新不成功时插入 比单独的 update insert 的方式效率要更高尤其是on条件下有唯一索引的时候效率更高。
使用场景
在写数据同步的脚本时常常会遇到这样的需求存在时更新不存在时插入
merge into语法
MERGE INTO [target-table] T --目标表 可以用别名
USING [source-table] S --数据源表 可以是表、视图、子查询
ON([conditional expression] ) --关联条件
WHEN MATCHED THEN --当关联条件成立时 更新、删除插入的where部分为可选
UPDATE [target-table] SET T.column S.column WHERE 限制条件
DELETE [target-table] WHERE 限制条件
WHEN NOT MATCHED THEN --当关联条件不成立时
INSERT (column,...) VALUES(,...)判断源表 S 和目标表 T 是否满足 ON 中的条件如果满足则用 S 表去更新 T 表如果不满足则将 S 表数据插入 T 表中。但是有很多可选项如下
普通模式只 update 或者只 insert无条件 insert 实现带 delete 的 update
测试表
-- 目标表
CREATE TABLE target ( ID NUMBER NOT NULL, NAME VARCHAR2 ( 12 ) NOT NULL, YEAR NUMBER
);
-- 源表
CREATE TABLE source (ID NUMBER NOT NULL,AID NUMBER NOT NULL,NAME VARCHAR2 ( 12 ) NOT NULL,YEAR NUMBER,CITY VARCHAR2 ( 12 )
);
-- 插入测试数据
INSERT INTO target
VALUES( 1, liuwei, 20 );
INSERT INTO target
VALUES( 2, zhangbin, 21 );
INSERT INTO target
VALUES( 3, fuguo, 20 );
INSERT INTO source
VALUES( 1, 2, zhangbin, 30, 吉林 );
INSERT INTO source
VALUES( 2, 4, yihe, 33, 黑龙江 );
INSERT INTO source
VALUES( 3, 3, fuguo, , 山东 );普通模式
merge使用注意点
1、如果using中的语句查询不出来数据是不会执行insert方法的因为这个语法是根据using 中的查询数据进行判断
merge into student a
using (select id from student where id 7) s
on (a.id s.id )
when matched thenupdate set a.student_name 小明二号
when not matched theninsert (id, student_name, fk_class) values (7, 小明, 2)2、on 中的条件记得过滤准确不然可能会执行全表更新
merge into student a
using (select count(1)cot,id from student group by id ) s
on (a.id s.id and cot 0)
when matched thenupdate set a.student_name 小明二号
when not matched theninsert (id, student_name, fk_class) values (7, 小明, 2)这么写的话可以看出明显的错误只要是id相等且cot大于0那么查询出的都大于0会执行全表更新 3、on 中的条件不能是更新操作列不然会报错ora-38104
merge into student a
using (select 7 as id from dual) s
on (a.id s.id)
when matched thenupdate set a.id 7
when not matched theninsert (id, student_name, fk_class) values (7, 小明, 2);参考 https://blog.csdn.net/weixin_44657888/article/details/124591434
https://www.jianshu.com/p/8f51ce60d9ba