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函数;



posted @   流云165  阅读(605)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App
点击右上角即可分享
微信分享提示