Oracle语法:merge into

merge into语句的用法

merge into 语句使用的场景:存在匹配条件的记录则更新,不存在则插入新的记录。

语法格式:

1
2
3
4
5
6
7
8
9
10
11
MERGE INTO 表名 别名1 
USING (table|view|sub_query) 别名2
ON (JOIN condition)
WHEN MATCHED THEN
--如果存在,更新
UPDATE SET
别名1.col1 = 别名2.col,
别名1.col2 = 别名2.col
WHEN NOT MATCHED THEN
--如果不存在,新增
INSERT (column1, column2) VALUES (别名2.column1, 别名2.column2);

判断B表和A表是否满足ON中条件,如果满足则执行满足后面的update SQL,如果不满足,则执行后面的insert SQL。

举例如下:

1
2
3
4
5
6
7
8
9
MERGE INTO  TEST T1

USING (SELECT '2' as ID, 'aaa' as NAME FROM dual) T2

ON (T1.ID=T2.ID)

WHEN MATCHED THEN UPDATE SET T1.NAME=T2.NAME

WHEN NOT MATCHED THEN INSERT (T1.ID, T1.NAME) VALUES (T2.ID, T2.NAME )

mybatis中批量merge into

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<update id="mergeinto">
merge into user_type a
using (
<foreach collection="list" item="item" separator="union all">
select
#{item.name,jdbcType=VARCHAR} as name,
#{item.type,jdbcType=VARCHAR} as type
from dual
</foreach>
) b
on (a.type = b.type)
when matched then
update set name = #{name}
when not matched then
insert (type,name) values(#{type},#{name})
</update>

注意从list中的对象取字段的值是用#{item.name}方式,而不是直接用#{name}

Mapper.java文件中代码是这样写的:

1
2
3
4
5

@Mapper
public interface UserTypeMapper {
void mergeinto(@Param("list") List<UserType> list);
}

------ 本文完 ------