Merge into 命令在Mybatis中如何使用
Merge into同一张表
模板
merge into 目标表 a
using 源表 b
on(a.条件字段1=b.条件字段1……)
when matched then update set a.更新字段=b.字段
when not macthed then insert into a(字段1,字段2……)values(值1,值2……)
源表b中查出的结果表示本次结果可以更改的结果集数量on(条件)中的结果是匹配原则
实现
merge into Table a USING (select count(1) as cnt from Table where ID = #{id, jdbcType=TIMESTAMP} and CHANNEL_ID = #{channelId, jdbcType=INTEGER} ) b on ( b.cnt>0 and a.ID= #{id, jdbcType=TIMESTAMP} and a.CHANNEL_ID = #{channelId, jdbcType=INTEGER} ) when MATCHED then update set a.COUNT = a.COUNT + 1 when not MATCHED then insert ( <if test="id != null"> a.ID, </if> <if test="channelId != null"> a.CHANNEL_ID, </if> <if test="count != null"> a.COUNT </if> ) values( <if test="id != null"> #{id,jdbcType=VARCHAR}, </if> <if test="channelId != null"> #{channelId,jdbcType=INTEGER}, </if> <if test="count != null"> #{count,jdbcType=INTEGER}, </if> )