当前位置:网站首页>mysql-批量更新
mysql-批量更新
2022-06-30 20:55:00 【zjun1001】
方法一:用update结合case、then实现
原始SQL语句
UPDATE baginfo_2021_09
SET channel_id = CASE id
WHEN 1 THEN 3
WHEN 2 THEN 4
WHEN 3 THEN 5
END,
stationId = CASE id
WHEN 1 THEN 6
WHEN 2 THEN 7
WHEN 3 THEN 8
END
WHERE id IN (1,2,3)
mybatis写法
<update id="updateBatchCaseThen" parameterType="java.util.List">
update baginfo_2022_03
<trim prefix="set" suffixOverrides=",">
<trim prefix="clientId =case" suffix="end,">
<foreach collection="list" item="i" index="index">
<if test="i.clientId!=null">
when id=#{i.id} then #{i.clientId}
</if>
</foreach>
</trim>
<trim prefix="model_version =case" suffix="end,">
<foreach collection="list" item="i" index="index">
<if test="i.model_version!=null">
when id=#{i.id} then #{i.model_version}
</if>
</foreach>
</trim>
<trim prefix="create_time =case" suffix="end,">
<foreach collection="list" item="i" index="index">
<if test="i.create_time!=null">
when id=#{i.id} then #{i.create_time}
</if>
</foreach>
</trim>
</trim>
where
<foreach collection="list" separator="or" item="i" index="index">
id=#{i.id}
</foreach>
</update>
方法二:用foreach循环实现
mybatis写法
<update id="batchUpdateBagInfo" parameterType="com.example.demo.entity.BagInfo">
<foreach collection="list" item="item" index="index" open="" close="" separator=";">
update baginfo_2022_03
<set>
<if test="item.clientId != null">
clientId = #{item.clientId},
</if>
<if test="item.model_version != null">
model_version = #{item.model_version},
</if>
<if test="item.create_time != null">
create_time = #{item.create_time},
</if>
</set>
where id = #{item.id}
</foreach>
</update>
用这种方法时,yml文件中配置的数据库URL,需要加上&allowMultiQueries=true
性能比较
mysql表数据量:2000w;一次更新数据量:1000
| 更新方法 | 更新总耗时 |
|---|---|
| 单条循环更新(for) | 1-3s |
| 方法1 | 110ms-180ms |
| 方法2 | 110ms-180ms |
总体比较,单条循环更新最慢的,想想也知道。而方法1和方法2的耗时相差不大。更高数量的批量更新,可能会导致结果不同,这里暂时没有测试。
边栏推荐
猜你喜欢
随机推荐
centos——开启/关闭oracle
19.04 distributor
Study on lumiprobe modified triphosphate biotin-11-utp
WebRTC系列-网络传输之本地scoket端口
Lumiprobe无铜点击化学解决方案
B_QuRT_User_Guide(34)
uniapp-生命周期/路由跳转
uniapp-路由uni-simple-router
在手机炒股开户安全吗?
Comparison between QT and other GUI Libraries
翻转链表II[翻转链表3种方式+dummyHead/头插法/尾插法]
Flinksql两个kafka 流可以进行join么?
Go学习笔记
DM8:生成DM AWR报告
k个一组反转链表
coredns 修改upstream
Web APIs 综合案例-Tab栏切换 丨黑马程序员
Lumiprobe copper free click chemical solution
CentOS - enable / disable Oracle
《大厂面试》之JVM篇21问与答








![[1175. prime number arrangement]](/img/f2/d427db03da151786ea1dfb7a76328a.png)
