欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

case when + forEach 实现多条件多值批量更新

程序员文章站 2022-04-01 11:23:23
case when + forEach 实现多条件多值批量更新1、单个条件 update mydata_table ...

case when + forEach 实现多条件多值批量更新

1、单个条件

   <update id="updateBatch" parameterType="java.util.List">
        update mydata_table
        <trim prefix="set" suffixOverrides=",">
            <trim prefix="status =case" suffix="end,">
                 <foreach collection="list" item="item" index="index">
                     <if test="item.status !=null ">
                         when id=#{item.id} then #{item.status}
                     </if>                    
                 </foreach>
            </trim>
        </trim>
        where id in
        <foreach collection="list" index="index" item="item" separator="," open="(" close=")">
            #{item.id,jdbcType=BIGINT}
        </foreach>
    </update>

2、多个条件

 <update id="updateBatch" parameterType="java.util.List">
    update demo_table
    <trim prefix="set" suffixOverrides=",">
        status=
        <foreach collection="list" item="item" open="case " close=" end,">
            when field2=#{item.field2} and company_id=#{item.field3} then #{item.status}
        </foreach>
        create_time =
        <foreach collection="list" item="item" open="case " close=" end,">
          when field2=#{item.field2} and company_id=#{item.field3} then
          <choose>
            <when test="item.createTime!=null">
              #{item.createTime}
            </when>
            <otherwise>now()</otherwise>
          </choose>
        </foreach>
    </trim>
    WHERE
    <foreach collection="list" item="item" open="( " separator=") or (" close=" )">
      device_num=#{item.field2} and company_id=#{item.field3}
    </foreach>
  </update>

注意:
foreach标签如果放在一条SQL外边的执行要比在一条SQL中写foreach然后根据条件循环更新的效率要低,数据量大的时候特别明显,建议foreach标签的使用写在一条SQL语句的中间

本文地址:https://blog.csdn.net/Sophia_0331/article/details/107598293

相关标签: ----【Mybatis】