在日常开发中,有时候会遇到批量更新操作,这时候最普通的写法就是循环遍历,然后一条一条地进行update操作。但是不管是在服务端进行遍历,还是在sql代码中进行遍历,都很耗费资源,而且性能比较差,容易造成阻塞。

Mysql没有提供直接的方法来实现批量更新,但可以使用case when语法来实现这个功能。

Mysql中代码示例:

UPDATE tablename
SET sort = CASE id
WHEN 1 THEN 'sort1'
WHEN 2 THEN 'sort2'
WHEN 3 THEN 'sort3'
END,
updateuserid = CASE id
WHEN 1 THEN 'updateuserid1'
WHEN 2 THEN 'updateuserid2'
WHEN 3 THEN 'updateuserid3'
END
WHERE id IN (1,2,3)

sql释义:

如果id为1,则sort的值为sort1,updateuserid的值为updateuserid1;

如果id为2,则sort的值为sort2,updateuserid的值为updateuserid2;

如果id为3,则sort的值为sort3,updateuserid的值为updateuserid3;以此类推。


Mybatis中代码示例:

<update id="updateBatch" parameterType="list">
update t_mt_sm_dept
<trim prefix="set" suffixOverrides=",">
<trim prefix=" sort = case" suffix="end,">
<foreach collection="list" item="i" index="index">
<if test="sort != '' and sort != null">
when id=#{i.id} then #{i.sort}
</if>
</foreach>
</trim>
<trim prefix="updateuserid = case" suffix="end,">
<foreach collection="list" item="i" index="index">
<if test="updateuserid != '' and updateuserid != null">
when id=#{i.id} then #{i.updateuserid}
</if>
</foreach>
</trim>
<trim prefix="updateusername = case" suffix="end,">
<foreach collection="list" item="i" index="index">
<if test="updateusername != '' and updateuserid != null">
when id=#{i.id} then #{i.updateusername}
</if>
</foreach>
</trim>
</trim>
where
<foreach collection="list" separator="or" item="i" index="index">
id = #{i.id}
</foreach>
</update>

java中代码:

   /**
* 批量修改排序
*/
int updateBatch(List<SmDept> smDeptList);

最新文章

  1. 深入理解javascript系列,读书笔记
  2. 收藏Javascript中常用的55个经典技巧
  3. rac one node在线relocation
  4. C#人爱学不学9[C#5.0异步实例+WPF自己的MVVM Async应用 1/12]
  5. javaweb学习总结(三十)——EL函数库
  6. LinkedBlockingQueue和ConcurrentLinkedQueue详细用法
  7. 记一个有想法却没能力实现的硬件产品——mp3校时闹钟
  8. Android内存管理(2)HUNTING YOUR LEAKS: MEMORY MANAGEMENT IN ANDROID PART 2
  9. 在Window IIS中安装运行node.js应用—你疯了吗
  10. 中文翻译:pjsip教程(二)之ICE穿越打洞:Interactive Connectivity Establishment简介
  11. WPF之Binding深入探讨--Darren
  12. SoC嵌入式软件架构设计II:没有MMU的CPU虚拟内存管理的设计和实现方法
  13. Ajax请求访问action推断文件是否存在
  14. 3433: [Usaco2014 Jan]Recording the Moolympics
  15. yuan 老师 之 Django
  16. Cisco N3K VPC+HSRP+ospf 配置
  17. 【代码笔记】iOS-获得现在的时间(2015-09-11)
  18. SQL Server 表分区之水平表分区
  19. thinkphp前台模版字符串截取
  20. liferay常用api总结

热门文章

  1. refreshContext(context)方法源码探究
  2. 事务回滚 try catch
  3. [HTML]HTML隐藏文本框的四种方式
  4. Kubernetes及Dashboard详细安装配置(Ubuntu14.04)
  5. 高性能网络通信框架 HP-Socket v5.2.1
  6. java+Selenium+TestNg搭建自动化测试架构(1)实现代码和数据的分离
  7. Python 编码的一些问题
  8. Linux环境安装、卸载Docker
  9. zk hdfs hadoop yarn hive 学习笔记
  10. 很不幸,装win10和Ubuntu双系统还是入坑了