MySQL 使用order by limit 分页重复问题

一、问题描述

执行以下sql,在数据没有插入删除的情况下,返回的数据可能不一致,导致线上出现重复数据

select xxx from table where xxx order by xxx limit offset

二、产生原因

mysql 5.6版本,mysqlorder by limit 做了一个优化,使用了priority queuepriority queue使用的是堆排序策略,在排序过程中虽然还要对n个数据进行排序,但是只需要消耗堆大小的内存就可以完成排序,提高了排序的空间效率

直接原因: 堆排序是不稳定的,当order by字段一致时,会造成输出结果顺序不一致。

官方文档:文档中明确指出顺序不确定

8.2.1.18 LIMIT Query Optimization

If multiple rows have identical values in the ORDER BY columns, the server is free to return those rows in any order, and may do so differently depending on the overall execution plan. In other words, the sort order of those rows is nondeterministic with respect to the nonordered columns.

【有道:如果多行具有相同的按列排序的值,服务器可以自由地以任何顺序返回这些行,并且根据总体执行计划可能以不同的方式返回。换句话说,这些行的排序顺序对于无序列是不确定的。】

三、解决方案

  1. 前端对分页结果去重
  2. 后端增加order by 字段

四、番外

在没有使用order by limit时,mysql是使用索引顺序

你可能感兴趣的:(SQL,sql,分页,重复)