Mybatis 数据库Mysql时间范围内数据查询非常慢的解决办法

表中数据量过大,目前已有300万条,查询user_name数据速度非常慢,如果不使用索引,想优化sql来提高查询速度,在调试过程中发现,写sql查询数据库时,传入时间段查询部分为:

<!--大于开始时间-->
 and sw.TIME >=to_date(CONCAT('2018-09-10', '00:00:00'),'yyyy-mm-dd hh24:mi:ss')
<!--小于结束时间-->
 and sw.TIME <=to_date(CONCAT('2018-09-10', '23:59:59'),'yyyy-mm-dd hh24:mi:ss')

在xml中传入String类型的开始时间和结束时间,写为:

<!--大于开始时间-->
 and sw.TIME >=to_date(CONCAT(#{start_time}, '00:00:00'),'yyyy-mm-dd hh24:mi:ss')
<!--小于结束时间-->
 and sw.TIME <=to_date(CONCAT(#{end_time}, '23:59:59'),'yyyy-mm-dd hh24:mi:ss')

查询后后台打印时间,超过10s;

后来查看数据库,该字段类型为Timestamp类型,在后台传入开始时间和结束时间,将它们先转化为Date类型,再传入sql设置jdbcType=TIMESTAMP:

优化如下:

<select  id="findResourcesByRoleIds"  resultType="string"  parameterType="map"  fetchSize="1000">
    select user_name from  g where 
<if test="start_time != null and start_time != '' ">
    and 
    <![CDATA[
        sw.TIME >=#{start_time,jdbcType=TIMESTAMP} 
    ]]>
</if>

<if test="end_time != null and end_time != '' ">
   and 
    <![CDATA[
        sw.TIME <=#{end_time,jdbcType=TIMESTAMP} 
    ]]>
</if>
</select>

后台打印时间为200ms;

注意点:

1.where条件字段建立索引;

2.使用fetchSize;

3.不要使用to_date函数;

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值