今天生产环境出行了一个分页排序错乱的问题,当时有点懵,用的mybatis-plus的分页插件实现的,往常也用但是没有出现这个 分页排序 错乱-丢失问题,说实话当时有点懵,经过排查分析
得出了结果:
Mybatis-plus 分页排序 错乱-丢失 其实归根结底是 order by 排序字段不稳定造成的,这一切都是因为使用的order by的字段不是唯一的,有很大可能出现相同值有多条,超过了每页的展示数量.而采用的不稳定的排序算法就会导致每次查询得到的结果都不一样,比如你第一次查询id为7的数据在第8位,而第二次查询时返回id为7的结果在第12位,如果一页只有10条数据,那么就会出现第一页和第二页中都会有id为7的这条数据.
问题复现
1.会出现以上情况的sql语句如下:
SELECT
a.id,
order_no,
run_time,
transfer_time,
a.create_time,
a.transfer_line_id,
b.transfer_line_name,
b.transfer_line_section_id,
b.transfer_line_section_name,
b.cooperation_line_section_id,
b.cooperation_line_section_name,
b.cooperation_line_id,
b.cooperation_line_name,
b.from_origin_time,
a.appoint_status,
a.transfer_order_no
FROM
table_1 a
INNER JOIN table_2 b ON a.cooperation_line_id = b.cooperation_line_id
AND a.cooperation_line_section_id = b.cooperation_line_section_id
AND a.transfer_line_id = b.transfer_line_id
WHERE
a.deleted = 0
GROUP BY order_no
ORDER BY transfer_time ASC //重点关注这一行排序sql
</select>
ORDER BY transfer_time 最终问题定位 transfer_time排序字段有重复值,不唯一
解决方法如下:
ORDER BY transfer_time ASC, a.id ASC,如果当前字段transfer_time一定要用的话,那么就再加一个唯一的字段搭配不唯一的字段排序,比如 a.id ASC,这样问题完美解决
注意:mysql5.5是不存在本文提到的问题的,5.6版本之后才出现了这种情况。