Mybatis查询一段时间内的数据出现数据缺失问题

问题:时间范围的查询会存在以下问题:

1、如果单纯采用年月日的形式会出现缺少最后一点的数据,比如要查询2015-09-16到2015-09-17,那么2015-09-17 01:00:00的数据不会被查询出来。无论是使用between and还是<=/>=的形式去实现都会有这样的问题。

解决方法:

1、如果是以年月日的形式,那么可以采用动态拼接字符串的形式,最后得到2015-09-16 00:00:00到2015-09-17 23:59:59,如果要更精确可以往毫秒级别加。

2、采用加1天的形式,比如使用DATE_ADD去增加最后一天,最终得到2015-09-16到2015-09-18。

3、在前端时间控件上采用更精确的输入,比如可以选择年月日时分秒的级别,但是如果要精确到毫秒级别的,需要另做处理,还是使用拼接字符串的形式,或者采用增加函数去增加毫秒级别。

4、如果采用DATE_ADD去增加1天,那么会面临一个问题,就是如果2017-09-18 00:00:00的数据就会被查出来,所以解决方法还是字符串拼接的形式会靠谱一些;或者如果用函数增加时间时,最好不要加满到1天。(初步想法,没实践)

5、如果想要优雅的解决,最完美的方式应该是时间戳的形式,比如将时间转成时间戳的形式去查询。

MyBatis的时间段查询方案:

1.查询到的数据与数据库数据条数不对应的写法

<select id="findCompayByName" resultType="com.doctor.cloud.recruit.biz.dto.CompanyDO">
     select * from r_company where 1 = 1
     <if test="startTime!=null and startTime!=''">
         and c1.create_time &gt;= #{startTime}
     </if>
     <if test="endTime!=null and endTime!=''">
         and c1.create_time &lt;= #{endTime}
     </if>
 </select>

2.解决方法1:使用contact函数拼接日期,其中日期字符串只取年月日(2020-08-14),方便拼接

<select id="findCompayByName" resultType="com.doctor.cloud.recruit.biz.dto.CompanyDO">
     select * from r_company where 1 = 1
     <if test="startTime!=null and startTime!=''">
         and c1.create_time &gt;= concat(#{startTime},' 00:00:00')
     </if>
     <if test="endTime!=null and endTime!=''">
         and c1.create_time &lt;= concat(#{endTime},' 23:59:59')
     </if>
 </select>

3.解决方法2:使用时间戳

<select id="findCompayByName" resultType="com.doctor.cloud.recruit.biz.dto.CompanyDO">
     select * from r_company where 1 = 1
     <if test="startTime!=null and startTime!=''">
         and c1.create_time &gt;= #{startTime,jdbcType=TIMESTAMP}
     </if>
     <if test="endTime!=null and endTime!=''">
         and c1.create_time &lt;= #{endTime,jdbcType=TIMESTAMP}
     </if>
 </select>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值