【MyBatis】【SQL】删除最快纪录诞生,从一千万条记录中删除八百万条仅用2分6秒
在 https://www.cnblogs.com/xiandedanteng/p/11669629.html 里我做个一个循环按时间查ID并删除之的程序,运行时间是4分7秒。
但是这个程序走了很多次没有必要的IO,也就是把不需要的指比如要删除的ID在Java所在的机器和DB服务器中传来传去,这个过程在没必要的耗时,不如把日期扔给DB告诉它删除之前的记录然后返回修改的记录数就行了,于是我书写了以下SQL语句:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.hy.mapper.EmpMapper"> <select id="selectById" resultType="com.hy.entity.Employee"> select id,name,age,cdate as ctime from emp where id=#{id} </select> <insert id="batchInsert"> insert into emp(name,age,cdate) values <foreach collection="list" item="emp" separator=","> (#{emp.name},#{emp.age},#{emp.ctime,jdbcType=TIMESTAMP}) </foreach> </insert> <insert id="singleInsert"> insert into emp(name,age,cdate) values (#{name},#{age},#{ctime,jdbcType=TIMESTAMP}) </insert> <select id="selectIdsByDate" resultType="java.lang.Long"> select id from emp where cdate<#{date,jdbcType=TIMESTAMP} limit 10000 </select> <delete id="deleteByIds"> delete from emp where id in <foreach collection="list" open="(" close=")" separator="," item="id" index="i"> #{id} </foreach> </delete> <delete id="deleteByDate"> delete from emp where id in (select id from (select id from emp where cdate<#{date,jdbcType=TIMESTAMP}) as tb) </delete> </mapper>
对应的接口是这样的:
package com.hy.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import com.hy.entity.Employee; public interface EmpMapper { Employee selectById(long id); int batchInsert(List<Employee> emps); // 用@Param标签指明和SQL的参数对应能避免出现org.apache.ibatis.binding.BindingException异常 int singleInsert(@Param("name")String name,@Param("age")int age,@Param("ctime")String ctime); List<Long> selectIdsByDate(String date); int deleteByIds(List<Long> ids); int deleteByDate(String date); }
Java程序则简单多了:
package com.hy.action; import java.io.Reader; import java.util.ArrayList; import java.util.List; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.apache.log4j.Logger; import com.hy.entity.Employee; import com.hy.mapper.EmpMapper; public class BatchDelete2 { private static Logger logger = Logger.getLogger(SelectById.class); public static void main(String[] args) throws Exception{ long startTime = System.currentTimeMillis(); Reader reader=Resources.getResourceAsReader("mybatis-config.xml"); SqlSessionFactory ssf=new SqlSessionFactoryBuilder().build(reader); reader.close(); SqlSession session=ssf.openSession(); try { EmpMapper mapper=session.getMapper(EmpMapper.class); int changed=mapper.deleteByDate("2018-02-02"); session.commit(); System.out.println("All deleted="+changed); }catch(Exception ex) { logger.error(ex); session.rollback(); }finally { session.close(); long endTime = System.currentTimeMillis(); logger.info("Time elapsed:" + toDhmsStyle((endTime - startTime)/1000) + "."); } } // format seconds to day hour minute seconds style // Example 5000s will be formatted to 1h23m20s private static String toDhmsStyle(long allSeconds) { String DateTimes = null; long days = allSeconds / (60 * 60 * 24); long hours = (allSeconds % (60 * 60 * 24)) / (60 * 60); long minutes = (allSeconds % (60 * 60)) / 60; long seconds = allSeconds % 60; if (days > 0) { DateTimes = days + "d" + hours + "h" + minutes + "m" + seconds + "s"; } else if (hours > 0) { DateTimes = hours + "h" + minutes + "m" + seconds + "s"; } else if (minutes > 0) { DateTimes = minutes + "m" + seconds + "s"; } else { DateTimes = seconds + "s"; } return DateTimes; } }
控制台输出也很有喜感:
All deleted=8035199 INFO [main] - Time elapsed:2m6s.
数据库里也达到了想要的结果:
时间减半,相对于循环删除的方案https://www.cnblogs.com/xiandedanteng/p/11669629.html ,优势是显而易见的。
本作代码下载地址:https://files.cnblogs.com/files/xiandedanteng/InsertMillionComparison2019101014.rar
--END-- 2019年10月14日10:44:47
【MyBatis】【SQL】删除最快纪录诞生,从一千万条记录中删除八百万条仅用2分6秒的更多相关文章
- 【MyBatis】【SQL】没有最快,只有更快,从一千万条记录中删除八百万条仅用1分9秒
这次直接使用delete from emp where cdate<'2018-02-02',看看究竟会发生什么. Mapper里写好SQL: <?xml version="1. ...
- SQL 从100万条记录中的到 成绩最高的记录
从100万条记录中的到 成绩最高的记录 问题分析:要从一张表中找到成绩最高的记录并不难,有很多种办法,最简单的就是利用TOP 1 select top 1 * from student order b ...
- sql 查询某个条件多条数据中最新的一条数据或最老的一条数据
sql 查询某个条件下多条数据中最新的一条数据或最老的一条数据 test_user表结构如下: 需求:查询李四.王五.李二创建的最初时间或者最新时间 1:查询最初的创建时间: SELECT * FRO ...
- SQL查找TCar表中同一辆车前后两条记录的CarId,两条记录中有多个字段值一样
查询同一个表中某一字段值相同的记录 select * from 表名 where 字段 in(select 字段 from 表名 group by 字段 having count(1)>1) s ...
- 【MyBatis】从一千万记录中批量删除八百万条,耗时4m7s
批量删除主要借助了MySql的limit函数,其次用了in删除. 代码如下: package com.hy.action; import java.io.Reader; import java.uti ...
- SpringMVC4+MyBatis+SQL Server2014 基于SqlSession实现读写分离(也可以实现主从分离)
前言 上篇文章我觉的使用拦截器虽然方便快捷,但是在使用读串还是写串上你无法控制,我更希望我们像jdbc那样可以手动控制我使用读写串,那么这篇则在sqlsession的基础上实现读写分离, 这种方式则需 ...
- sql server数据库中删除的过程
这是在vb中的一个对数据库中数据的删除过程,点击按钮后程序第一句则是将你要删除的那条记录的位置作为书签保存到myBookmark这个变量里面,然后选择确定删除的话,首先执行if语句下的第一句 mrc. ...
- MySQL中删除数据的两种方法
转自:http://blog.csdn.net/apache6/article/details/2778878 1. 在MySQL中有两种方法可以删除数据: 一种是delete语句,另一种是trunc ...
- easyui的datagrid删除一条记录后更新出问题
1.问题 如果先删除一条记录,然后不选中一条记录,去更新一条,默认是有选中的记录的,就是被删除的那条记录. 2.解决方法 $("#dg").datagrid('uncheckAll ...
随机推荐
- jQuery EasyUI 拖放 – 基本的拖动和放置
jQuery EasyUI 拖放 - 基本的拖动和放置 在jQuery EasyUI中,可以实现HTML元素的基本拖动和放置. <div id="dd1" class=&qu ...
- Git---初入开源代码管理库的学习过程003
Git常用命令总结 上接<Git 初入开源代码管理库的学习过程>学了一周Git,基本有了个认识.每一位比我厉害的,都是大牛,网上找了几篇博客和教材(感谢你们),边学习边实践用了四天,写笔记 ...
- shell脚本基础编写
shell脚本的格式 名称:Shell 脚本文件的名称可以任意,但为了避免被误以为是普通文件,建议将 .sh 后缀加上,以表示是一个脚本文件. shell 脚本中一般会出现三种不同的元素: 第一行的脚 ...
- redis.conf 文件解释
# Redis示例配置文件 # 注意单位问题:当需要设置内存大小的时候,可以使用类似1k.5GB.4M这样的常见格式: # # 1k => 1000 bytes # 1kb => 1024 ...
- C语言例题
1.连接两个字符串 将两个字符串连接,不要用stract函数 2.求矩阵外围元素之和 求3行3列矩阵的外围元素之和. 3.求矩阵主对角线和副对角线元素之和 求5行5列矩阵的主对角线和副对角线元素之和. ...
- 在maven项目中如何引入另外一个项目(转)
原文链接:https://blog.csdn.net/jianfpeng241241/article/details/52654352 1 在Myeclipse中准备两个maven demo. , ...
- MFC的静态链接、动态链接
项目属性页面可以查看更改编译方式,推荐使用静态编译.也可以在创建MFC项目时选择静态编译. 标准Windows库,使用的是系统API,Win32是面向API的编程平台.Win32项目使用的是此编译方式 ...
- Luogu P5022 旅行 搜索+贪心
好吧...一直咕..现在才过...被卡常卡到爆... 写的垃圾版本,$n^2$无脑删边..可以发现走出来的是棵树...更优秀的及数据加强版先咕着...一定写.qwq #include<cstdi ...
- 解决Spring AOP Controller 不生效
在spring-mvc.xml文件中,进行以下配置,就可以实现在Controller中, 方法一:最简单的,在spring-mvc.xml配置文件中,添加以下语句 spring-mvc.xml < ...
- on(events,[selector],[data],fn) 在选择元素上绑定一个或多个事件的事件处理函数
on(events,[selector],[data],fn) 概述 在选择元素上绑定一个或多个事件的事件处理函数.大理石平台精度等级 on()方法绑定事件处理程序到当前选定的jQuery对象中的元素 ...