更新單條記錄
UPDATE course SET name = 'course1' WHERE id = 'id1';
更新多條記錄的同一個字段為同一個值
UPDATE course SET name = 'course1' WHERE id in ('id1', 'id2', 'id3);
更新多條記錄為多個字段為不同的值
比較普通的寫法,是通過循環,依次執行update語句。
Mybatis寫法如下:
<update id="updateBatch" parameterType="java.util.List">
<foreach collection="list" item="item" index="index" open="" close="" separator=";">
update course
<set>
name=${item.name}
</set>
where id = ${item.id}
</foreach>
</update>
一條記錄update一次,性能比較差,容易造成阻塞。
PostgreSQL沒有提供直接的方法來實現批量更新,但可以使用case when語法來實現這個功能。
UPDATE course
SET name = CASE id
WHEN 1 THEN 'name1'
WHEN 2 THEN 'name2'
WHEN 3 THEN 'name3'
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)
這條sql的意思是,如果id為1,則name的值為name1,title的值為New Title1;依此類推。
在Mybatis中的配置則如下:
<update id="updateBatch" parameterType="list">
update course
<trim prefix="set" suffixOverrides=",">
<trim prefix="peopleId =case" suffix="end,">
<foreach collection="list" item="i" index="index">
<if test="i.peopleId!=null">
when id=#{i.id} then #{i.peopleId}
</if>
</foreach>
</trim>
<trim prefix=" roadgridid =case" suffix="end,">
<foreach collection="list" item="i" index="index">
<if test="i.roadgridid!=null">
when id=#{i.id} then #{i.roadgridid}
</if>
</foreach>
</trim>
<trim prefix="type =case" suffix="end," >
<foreach collection="list" item="i" index="index">
<if test="i.type!=null">
when id=#{i.id} then #{i.type}
</if>
</foreach>
</trim>
<trim prefix="unitsid =case" suffix="end," >
<foreach collection="list" item="i" index="index">
<if test="i.unitsid!=null">
when id=#{i.id} then #{i.unitsid}
</if>
</foreach>
</trim>
</trim>
where
<foreach collection="list" separator="or" item="i" index="index" >
id=#{i.id}
</foreach>
</update>
<update id="updateUserLog" parameterType="java.util.List">
update ps_user_log
SET dept_id =
<foreach collection="list" item="item" index="index"
separator=" " open="case id" close="end">
when #{item.id} then #{item.deptId}
</foreach>
, type =
<foreach collection="list" item="item" index="index"
separator=" " open="case id" close="end">
when #{item.id} then #{item.type}
</foreach>
where id in (
<foreach collection="list" item="item" index="index"
separator=",">
#{item.id}
</foreach>
)
</update>