转载地址1:https://blog.csdn.net/u014520745/article/details/52416002
转载地址2:https://blog.csdn.net/xyjawq1/article/details/74129316
首先介绍sql语法如何做批量update
mysql 批量更新如果一条条去更新效率是相当的慢, 循环一条一条的更新记录,一条记录update一次,这样性能很差,也很容易造成阻塞。
mysql 批量更新共有以下四种办法
1、.replace into 批量更新
replace into test_tbl (id,dr) values (1,'2'),(2,'3'),...(x,'y');
2、insert into ...on duplicate key update批量更新
insert into test_tbl (id,dr) values (1,'2'),(2,'3'),...(x,'y') on duplicate key update dr=values(dr);
3.创建临时表,先更新临时表,然后从临时表中update
- create temporary table tmp(id int(4) primary key,dr varchar(50));
- insert into tmp values (0,'gone'), (1,'xx'),...(m,'yy');
- update test_tbl, tmp set test_tbl.dr=tmp.dr where test_tbl.id=tmp.id;
注意:这种方法需要用户有temporary 表的create 权限。
4、使用mysql 自带的语句构建批量更新
mysql 实现批量 可以用点小技巧来实现:
- UPDATE yoiurtable
- SET dingdan = CASE id
- WHEN 1 THEN 3
- WHEN 2 THEN 4
- WHEN 3 THEN 5
- END
- WHERE id IN (1,2,3)
这句sql 的意思是,更新dingdan 字段,如果id=1 则dingdan 的值为3,如果id=2 则dingdan 的值为4……
where部分不影响代码的执行,但是会提高sql执行的效率。确保sql语句仅执行需要修改的行数,这里只有3条数据进行更新,而where子句确保只有3行数据执行。
如果更新多个值的话,只需要稍加修改:
- UPDATE categories
- SET dingdan = 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)
到这里,已经完成一条mysql语句更新多条记录了。
php中用数组形式赋值批量更新的代码:
- $display_order = array(
- 1 => 4,
- 2 => 1,
- 3 => 2,
- 4 => 3,
- 5 => 9,
- 6 => 5,
- 7 => 8,
- 8 => 9
- );
- $ids = implode(',', array_keys($display_order));
- $sql = "UPDATE categories SET display_order = CASE id ";
- foreach ($display_order as $id => $ordinal) {
- $sql .= sprintf("WHEN %d THEN %d ", $id, $ordinal);
- }
- $sql .= "END WHERE id IN ($ids)";
- echo $sql;
这个例子,有8条记录进行更新。代码也很容易理解,你学会了吗
更新 100000条数据的性能就测试结果来看,测试当时使用replace into性能较好。
replace into 和 insert into on duplicate key update的不同在于:
- replace into 操作本质是对重复的记录先delete 后insert,如果更新的字段不全会将缺失的字段置为缺省值,用这个要悠着点否则不小心清空大量数据可不是闹着玩的。
- insert into 则是只update重复记录,不会改变其它字段。
然后正式开始mybatis中批量update
逐条更新
这种方式显然是最简单,也最不容易出错的,即便出错也只是影响到当条出错的数据,而且可以对每条数据都比较可控,更新失败或成功,从什么内容更新到什么内容,都可以在逻辑代码中获取。代码可能像下面这个样子:
updateBatch(List<MyData> datas){
for(MyData data : datas){
try{
myDataDao.update(data);//更新一条数据,mybatis中如下面的xml文件的update
}
catch(Exception e){
...//如果更新失败可以做一些其他的操作,比如说打印出错日志等
}
}
}
//mybatis中update操作的实现
<update>
update mydata
set ...
where ...
</update>
这种方式最大的问题就是效率问题,逐条更新,每次都会连接数据库,然后更新,再释放连接资源(虽然通过连接池可以将频繁连接数据的效率大大提高,抗不住数据量大),这中损耗在数据量较大的时候便会体现出效率问题。这也是在满足业务需求的时候,通常会使用上述提到的第二种批量更新的实现(当然这种方式也有数据规模的限制,后面会提到)。 sql批量更新
一条sql
语句来批量更新所有数据,下面直接看一下在mybatis
中通常是怎么写的(去掉mybatis
语法就是原生的sql
语句了,所有就没单独说sql
是怎么写的)。<update id="updateBatch" parameterType="java.util.List">
update mydata_table
set status=
<foreach collection="list" item="item" index="index"
separator=" " open="case ID" close="end">
when #{item.id} then #{item.status}
</foreach>
where id in
<foreach collection="list" index="index" item="item"
separator="," open="(" close=")">
#{item.id,jdbcType=BIGINT}
</foreach>
</update>
其中when...then...
是sql
中的"switch"
语法。这里借助mybatis
的<foreach>
语法来拼凑成了批量更新的sql
,上面的意思就是批量更新id
在updateBatch
参数所传递List
中的数据的status
字段。还可以使用<trim>
实现同样的功能,代码如下:
<update id="updateBatch" parameterType="java.util.List">
update mydata_table
<trim prefix="set" suffixOverrides=",">
<trim prefix="status =case" suffix="end,">
<foreach collection="list" item="item" index="index">
when id=#{item.id} then #{item.status}
</foreach>
</trim>
</trim>
where id in
<foreach collection="list" index="index" item="item" separator="," open="(" close=")">
#{item.id,jdbcType=BIGINT}
</foreach>
</update>
<trim>
属性说明
1.prefix,suffix
表示在trim
标签包裹的部分的前面或者后面添加内容
2.如果同时有prefixOverrides,suffixOverrides
表示会用prefix,suffix
覆盖Overrides
中的内容。
3.如果只有prefixOverrides,suffixOverrides
表示删除开头的或结尾的xxxOverides
指定的内容。
上述代码转化成sql
如下:
update mydata_table
set status =
case
when id = #{item.id} then #{item.status}//此处应该是<foreach>展开值
...
end
where id in (...);
当然这是最简单的批量更新实现,有时候可能需要更新多个字段,那就需要将
<trim prefix="status =case" suffix="end,">
<foreach collection="list" item="item" index="index">
when id=#{item.id} then #{item.status}
</foreach>
</trim>
复制拷贝多次,更改prefix
和when...then...
的内容即可.而如果当需要为某个字段设置默认值的时候可以使用else
<trim prefix="status =case" suffix="end,">
<foreach collection="list" item="item" index="index">
when id=#{item.id} then #{item.status}
</foreach>
else default_value
</trim>
还有更常见的情况就是需要对要更新的数据进行判断,只有符合条件的数据才能进行更新,这种情况可以这么做:
<trim prefix="status =case" suffix="end,">
<foreach collection="list" item="item" index="index">
<if test="item.status !=null and item.status != -1">
when id=#{item.id} then #{item.status}
</if>
</foreach>
</trim>
这样的话只有要更新的list
中status != null && status != -1
的数据才能进行status
更新.其他的将使用默认值更新,而不会保持原数据不变.如果要保持原数据不变呢?即满足条件的更新,不满足条件的保持原数据不变,简单的来做就是再加一个<if>
,因为mybatis
中没有if...else...
语法,但可以通过多个<if>
实现同样的效果,如下:
<trim prefix="status =case" suffix="end,">
<foreach collection="list" item="item" index="index">
<if test="item.status !=null and item.status != -1">
when id=#{item.id} then #{item.status}
</if>
<if test="item.status == null or item.status == -1">
when id=#{item.id} then mydata_table.status //这里就是原数据
</if>
</foreach>
</trim>
整体批量更新的写法如下:
<update id="updateBatch" parameterType="java.util.List">
update mydata_table
<trim prefix="set" suffixOverrides=",">
<trim prefix="status =case" suffix="end,">
<foreach collection="list" item="item" index="index">
<if test="item.status !=null and item.status != -1">
when id=#{item.id} then #{item.status}
</if>
<if test="item.status == null or item.status == -1">
when id=#{item.id} then mydata_table.status//原数据
</if>
</foreach>
</trim>
</trim>
where id in
<foreach collection="list" index="index" item="item" separator="," open="(" close=")">
#{item.id,jdbcType=BIGINT}
</foreach>
</update>
这种批量跟心数据库的方式可以在一次数据库连接中更新所有数据,避免了频繁数据库建立和断开连接的开销,可以很大程度的提高数据更新效率。但是这样的问题是如果这个过程中更新出错,将很难知道具体是哪个数据出错,如果使用数据自身的事务保证,那么一旦出错,所有的更新将自动回滚。而且通常这种方式也更容易出错。因此通常的使用的方案是进行折中,也就是一次批量更新一部分(分页进行更新,比如说一共有1000条数据,一次更新100条)。这样可以分担出错的概率,也更容易定位到出错的位置。
当然如果数据量确实很大的时候,这种批量更新也一样会导致更新效率低下(比如说一次更新100条,那如果10亿条数据呢,一样要批量更新1000万次,建立和断开1000万次数据库,这个效率是无法承受的)。这时候也许只能考虑其他方案了,比如引入缓存机制等。