UPDATE tableName
SET orderId = CASE id
WHEN 1 THEN 3
WHEN 2 THEN 4
WHEN 3 THEN 5
END
WHERE id IN (1,2,3)
这句sql 的意思是,更新orderId 字段,如果id=1 则orderId 的值为3,如果id=2 则orderId 的值为4……
where部分不影响代码的执行,但是会提高sql执行的效率。确保sql语句仅执行需要修改的行数,这里只有3条数据进行更新,而where子句确保只有3行数据执行。
如果更新多个值的话,只需要稍加修改:
多字段:
UPDATE categories
SET orderId = CASE id
WHEN 1 THEN 3
WHEN 2 THEN 4
WHEN 3 THEN 5
END,
title = CASE id
WHEN 1 THEN 'New Title 1'
WHEN 2 THEN 'New Title 2'
WHEN 3 THEN 'New Title 3'
END
WHERE id IN (1,2,3)
单个字段修改:
<update id="BatchUpdate" parameterType="map">
update activity_gift_status
<set>
<trim prefix="ref_activity_type=case" suffix="end,">
<foreach collection="list" item="item" index="index">
<if test="item.refActivityType !=null">
when ref_activity_id=#{item.refActivityId} then #{item.refActivityType}
</if>
</foreach>
</trim>
</set>
where
activity_gift_status_id in
<foreach collection="list" item="item" index="index" separator="," open="(" close=")">
#{item.activityGiftStatusId}
</foreach>
</update>
多条件修改:
<update id="updateByBatch" parameterType="list">
update message_notice_task
<trim prefix="set" suffixOverrides=",">
<trim prefix=" call_back_status = case" suffix="end,">
<foreach collection="list" item="item" index="index">
<if test="item.callBackStatus !=null">
when task_id = #{item.taskId} then #{item.callBackStatus}
</if>
</foreach>
</trim>
<trim prefix="reason = case" suffix="end,">
<foreach collection="list" item="item" index="index">
<if test="item.reason !=null">
when task_id = #{item.taskId} then #{item.reason}
</if>
</foreach>
</trim>
<trim prefix="reason_text = case" suffix="end,">
<foreach collection="list" item="item" index="index">
<if test="item.reasonText !=null">
when task_id = #{item.taskId} then #{item.reasonText}
</if>
</foreach>
</trim>
</trim>
<where>
AND task_id in
<foreach collection="list" item="item" index="index" separator="," open="(" close=")">
#{item.taskId}
</foreach>
</where>
</update>