数据库不提供想多条插入类似的语法,但是我们可以借助于case when来拼出一个常sql,当然这还是一条语句,

update tabel1
set 字段1 = case 条件字段 when 条件值1 then 字段1的值1 when 条件值2 then 字段1的值2 end
  , 字段2 = case 条件字段 when 条件值 then 字段2的值 end
  , 字段3 = case 条件字段 when 条件值 then CONCAT(字段3, 追加值) end
where 共有条件 = 条件值;

mybatis中使用如下

<update id="updateInfo">
    update table1 set 字段1=
        <foreach collection="base" item="base" open="case 条件字段" close="else 字段1 end" separator=" ">
          when #{base.条件值} then #{base.字段1的值}
        </foreach>
         , 字段2=
        <foreach collection="base" item="base" open="case 条件字段" close="else 字段2 end" separator=" ">
          when #{base.条件值} then #{base.字段2的值}
        </foreach>
         , 字段3=
        <foreach collection="base" item="base" open="case 条件字段" close="else 字段3 end" separator=" ">
          when #{base.条件值} then #{base.字段3的值}
        </foreach>
         , 字段4=
        <foreach collection="base" item="base" open="case 条件字段" close="else 字段4 end" separator=" ">
          when #{base.条件值} then #{base.字段4的值}
        </foreach>
         , 字段5=
        <foreach collection="base" item="base" open="case 条件字段" close="else 字段5 end" separator=" ">
          when #{base.条件值} then #{base.字段5的值}
        </foreach>
         , 字段6=
        <foreach collection="base" item="base" open="case 条件字段" close="else 字段6 end" separator=" ">
          when #{base.条件值} then CONCAT(IFNULL(字段6,''),IFNULL(#{base.字段6的值},''))
        </foreach>
          where 字段6=#{条件值};
  </update>

注意CONCAT进行字符串追加时,如果其中有任何一个时null值则结果一定时null解决办法时使用IFNULL(value,’’),将null值替换成空串就行了

更多推荐