mysql並沒有提供直接的方法來實現批量更新,但是可以用點小技巧來實現。
這里使用了case when
這個小技巧來實現批量更新。
舉個例子:
UPDATE 表名 SET
display_order = CASE id
WHEN 1 THEN 3
WHEN 2 THEN 4
WHEN 3 THEN 5
END
WHERE id IN (1,2,3)
這句sql的意思是,更新display_order 字段:
如果id=1 則display_order 的值為3,
如果id=2 則 display_order 的值為4,
如果id=3 則 display_order 的值為5。
即是將條件語句寫在了一起。
這里的where部分不影響代碼的執行,但是會提高sql執行的效率。
確保sql語句僅執行需要修改的行數,這里只有3條數據進行更新,而where子句確保只有3行數據執行。
單個條件批量更新:
<update id="updateBatch" parameterType="java.util.List">
update 表名
<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>
多條件批量更新:
<update id="updateBatch" parameterType="java.util.List">
update 表名
<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>