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

发布时间 2023-06-01 17:40:05作者: 流云165

表中数据量过大,目前已有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函数;