环境:mysql + mybatis;
问题来源:查询结果和count()计算总行数结果对不上;
我的想法:
1、count()结果不对,是因为count针对了多,如果我针对一count是不是结果就对了呢?(没找对问题点还不自知!!!)
2、开始写测试代码,发现问题并不在count,在limit;
3、突发奇想(将错就错),我先对一分页后查询呢?
result_model
<resultMap id="Test_Map" type="com.sy.pangu.pm.entity.test.TaskTestInfo">
<!-- 一 -->
<result column="task_id" jdbcType="VARCHAR" property="taskId"/>
<result column="task_type" jdbcType="VARCHAR" property="taskType"/>
<!-- 多 -->
<collection property="extendInfos" ofType="com.sy.pangu.pm.entity.test.ExtendInfo">
<result column="file_id" jdbcType="VARCHAR" property="fileId"/>
<result column="up_type" jdbcType="VARCHAR" property="upType"/>
</collection>
</resultMap>
查询语句代码块(条件查询写完整,因为条件放在引入点整块太乱了)
<sql id="Test_SQL">
SELECT
-- 一
t.task_id,
t.task_type,
-- 多
e.file_id,
e.up_type
FROM
pm_task_info t
LEFT JOIN pm_task_extend e ON e.task_id = t.task_id
WHERE
t.task_id IN ( '19083001200', '19083001202' )
</sql>
分页查询和统计语句
<select id="selectOneToManyPage" parameterType="map" resultMap="Test_Map">
select a.*
from (
<include refid="Test_SQL"/>
) a
right join (
-- 对一分页
select distinct task_id from
(
<include refid="Test_SQL"/>
) inner_b
LIMIT ${start} , ${limit}
) b on a.task_id = b.task_id
</select>
<select id="selectOneToManyCountForMany" resultType="java.lang.Long">
-- 对一统计
select count(distinct task_id)
from (
<include refid="Test_SQL"/>
) a
</select>
测试代码
Map page = new HashMap();
page.put("start", 0);//
page.put("limit", 1);
List<TaskTestInfo> tasks = testMapper.selectOneToManyPage(page);
long total = testMapper.selectOneToManyCountForMany();
Map page1 = new HashMap();
page1.put("start", 1);//
page1.put("limit", 1);
List<TaskTestInfo> tasks1 = testMapper.selectOneToManyPage(page1);
long total1 = testMapper.selectOneToManyCountForMany();
Map page2 = new HashMap();
page2.put("start", 2);//
page2.put("limit", 1);
List<TaskTestInfo> tasks2 = testMapper.selectOneToManyPage(page2);
long total2 = testMapper.selectOneToManyCountForMany();
结果展示
一有2条,多有5条。分页查询,一次差一条,第三次就查不到数据,貌似结果没问题???
看一下sql查询模块的结果(反正结果是符合了)
解决一对多分页另一种思路
思路:如果把多并入一是不是就解决问题了呢?
select t.task_id, GROUP_CONCAT('[','"fileId":',e.file_id,',','"upType":',e.up_type,']') many_field from pm_task_info t
left join pm_task_extend e on t.task_id = e.task_id
WHERE
t.task_id IN ( '19083001200', '19083001202' )
group by t.task_id
结果
说明:多已经并列成一行了,再关联一下主表,嘿嘿,是不是变成一对一了?剩下那就正常分页就行了。