查询数据多出一天数据的情况分析
小编今天遇到前辈留下的一个系统的历史遗留bug,查询报表数据,本来查询时间是4-01到4-30的数据,但是查出的数据确多出了一天的数据,先看代码
Controller层
@RequestMapping("/gethcsebd_result")
public @ResponseBody DataGridResultInfo getHighChartsEmgByDate(
HspemginfQueryDto hspemginfQueryDto) throws Exception{
Date enddate=DateUtil.afterNDay(hspemginfQueryDto.getEnddate(), 1);
hspemginfQueryDto.setEnddate(enddate);
List<HighChartsDemoCustom> list=hspreportService.getHighChartsEmg(hspemginfQueryDto);
DataGridResultInfo dataGridResultInfo = new DataGridResultInfo();
dataGridResultInfo.setRows(list);
return dataGridResultInfo;
}
Mapper.xml层
<select id="getHighChartsEmg" parameterType="activetech.hospital.pojo.dto.HspemginfQueryDto"
resultType="activetech.base.pojo.dto.HighChartsDemoCustom">
select info name,
(select count(emg_dep_cod)count from hsp_emg_inf where emg_dep_cod=infocode
and to_char(hsp_emg_inf.emg_dat,'yyyy/mm/dd')<![CDATA[>=]]> to_char(#{startdate},'yyyy/mm/dd')
and to_char(hsp_emg_inf.emg_dat,'yyyy/mm/dd')<![CDATA[<=]]> to_char(#{enddate},'yyyy/mm/dd')) count from dstdictinfo
where typecode = 'MOD_LVL_COD'
</select>
这两块主要代码,表面上看是没有问题,但是,查询的数据就是不对,调试了各个节点的时间格式,发现时间确实没有问题,但是细细分析后发现,问题还是很严重的。
1.首先,页面传过来的enddate是04-30,我们下意识会将该时间加一天来查找04-30当天的数据,所以此时后台接收的是04-01 到 05-01
2.此时分析sql代码,>=startdate and <=enddate,逻辑看着也没有问题,但是此时小编发现,时间的to_char方法使用的是yyyy/mm/dd,也就是说时间精确到天,那么后台sql的时间条件变成了
04-01 >=startdate and 05-01<=enddate
所以造成了05-01的数据也被查出来了。
解决办法
1).将controller层的enddate时间加一天的代码删除
2).将sql中
and to_char(hsp_emg_inf.emg_dat,'yyyy/mm/dd')<![CDATA[<=]]> to_char(#{enddate},'yyyy/mm/dd')
改成
and to_char(hsp_emg_inf.emg_dat,'yyyy/mm/dd')<![CDATA[<]]> to_char(#{enddate},'yyyy/mm/dd')
OK!
总结!遇到时间问题一定要注意两头极值的问题。