Mysql order by和limit混合使用问题

问题描述:

本周在工作中遇到一个问题,分页查询数据,不同页之中出现了相同的数据。条件筛选之后根据业务日期排序并分页,业务日期相同的有106条数据,50条一页。结果在第一页和第二页都出现了同样的一条数据。


为什么呢?

order by 和 limit一起使用会存在一些问题。
原文如下:

If you combine LIMIT row_count with ORDER BY, MySQL stops sorting as soon as it has found the first row_count rows of the sorted result, rather than sorting the entire result. If ordering is done by using an index, this is very fast. If a filesort must be done, all rows that match the query without the LIMIT clause are selected, and most or all of them are sorted, before the first row_count are found. After the initial rows have been found, MySQL does not sort any remainder of the result set.

One manifestation of this behavior is that an ORDER BY query with and without LIMIT may return rows in different order, as described later in this section.

大概意思:

如果你把order BY 和 limit N 混合使用,mysql会在找排序结果中的第一个 “第N条记录” 时就停止,而不会排序整个结果集。如果排序是通过索引完成的,那么这个操作就会非常快。如果必须要通过数据文件排序,所有符合查询条件的记录都将被选中,并且所有的数据都将被排序,直到第一个 “第N条记录” 被找到。在第一条的数据都被找到之后,mysql不会继续把结果中剩余的数据进行排序。

这种实现行为的表现之一就是order by查询 在配合 limit 使用和不配合limit使用的情况下的返回值,排序情况是不同的。

简单来说,当我们执行 order by XXXX limit N的时候。

  1. 根据条件过滤数据
  2. 把结果集放入待排序块
  3. 把待排序块中一条条放入已排序块中进行排序
  4. 当已排序块中的数据等于N,或者待排序块中的数据等于0时,返回结果

这是mysql5.7的优化 也就是说5.7之前的版本是没有这个问题的。

至于mysql的排序算法,后期有时间再去了解一下。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值