问题:使用mybatis-plus关联多表分页记录的时候。得到的总数记录数不正确。先看代码
int rank = 0 ;
QueryWrapper queryWrapper = new QueryWrapper<>();
Page page = new Page<>(statisticQueryVo.getPage(), statisticQueryVo.getSize());
queryWrapper.eq("su.is_delete",0);
if (StrUtil.isNotEmpty(statisticQueryVo.getName())) {
queryWrapper.like("su.real_name","%"+statisticQueryVo.getName()+"%");
}
if (StrUtil.isNotEmpty(statisticQueryVo.getDepartmentId())) {
queryWrapper.eq("su.department_id",statisticQueryVo.getDepartmentId());
}
if (statisticQueryVo.getYear() != null) {
queryWrapper.eq("fd.year",statisticQueryVo.getYear());
}
//备用查询总数方法
//Long total = statisticInfoDao.getTotal(queryWrapper);
//该条件不能放到上面,会出现异常
//坑爹的点,需要手动把sql的优化关闭。不然计数的时候只会查主表的记录数
page.setOptimizeCountSql(false);
queryWrapper.orderByDesc("so.create_time");
Page selectPage = statisticInfoDao.statisticsInfo(page, queryWrapper);
List<StatisticInfoVo> statisticInfoVos = selectPage.getRecords();
long total = selectPage.getTotal();
@Select("SELECT\n" +
"su.real_name as realName,so.depart_name as departmentName,\n" +
"fd.duration,fd.year,es.score as testScore\n" +
"FROM\n" +
"sys_userinfo as su\n" +
"LEFT JOIN sys_organization as so ON so.id = su.department_id\n" +
"LEFT JOIN file_duration as fd ON fd.user_id = su.id\n" +
"LEFT JOIN exam_score as es ON es.user_id = su.id ${ew.customSqlSegment}\n")
Page<StatisticInfoVo> statisticsInfo(Page page, @Param("ew") Wrapper queryWrapper);
重点是这里,需要手动关闭count优化
//坑爹的点,需要手动把sql的优化关闭。不然计数的时候只会查主表的记录数
page.setOptimizeCountSql(false);
源码中是默认开启的,如图
/**
* 自动优化 COUNT SQL
*/
protected boolean optimizeCountSql = true;
如果不关闭将会导致计算总记录数据的时候,sql语句会丢弃后面的子查询,造成记录数结果不正确。
==> Preparing: SELECT COUNT(*) FROM sys_userinfo AS su WHERE (su.is_delete = ?)
==> Parameters: 0(Integer)
<== Columns: count
<== Row: 2
<== Total: 1