mybatis通过关键条件查询后有就修改没有新增

转自:https://www.cnblogs.com/Springmoon-venn/p/8519592.html

mybatis 使用merge into,跟一般的update写法相同:

<update id="mergeinfo">
        merge into user_type a
        using ( select #{name} as name, #{type} as type from dual ) b
        on (a.type = b.type)
        when not matched then
        insert  (type,name) values(#{type},#{name})
        when matched then
        update set name = #{name} where type = #{type}
</update>

传入字段 name、type,使用 “select #{name} as name, #{type} as type from dual”,构建一个子查询建别名 “b”,

目标表“a” 的type字段,与子查询表“b”的type字段比较:

  如果不匹配:

    执行 :“insert (type,name) values(#{type},#{name})”

  如果匹配:

    执行:“update set name = #{name} where type = #{type}”

主要on 后面的括号不能省

原文地址:https://www.cnblogs.com/cuijiade/p/9606316.html