MySQL Order By排序混乱问题

问题描述

    做积分排行榜页面时, 发现vue key值重复,如下:

a494899da5fff619851364885c3cf464272c6325

    此处的key值为数据在mysql中的主键,在排除前端错误之后,判断是mysql排序问题. mysql排序sql如下:

b6f23b857d91e484db9ee5a174befdebffd1a96f

    该sql使用score和create_time作为排序条件,查询结果如下:

e412e9f2bd38b1dc310a87f777b55cbb2b0426ec5e7d50809220aff4f35779a3b689a6163efd51fd

       结果确实乱序了。

查找解决方案

       查找原因,发现score和create_time存在相同值,当相同的score和create_time有多条数据时,mysql会对这些数据进行随机排序,所以同一条SQL查出的结果会出现排序不同的情况。

       mysql官网对此有一些描述:

     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.
       如果order by的字段有多个行都有相同的值,mysql会以随机的顺序返回查询结果,并且依据具体的执行计划会有不同。
     If it is important to ensure the same row order with and without LIMIT, 
     include additional columns in the ORDER BY clause to make the order deterministic. 
     For example, if id values are unique, you can make rows for a given category value appear in id order by sorting like this:
      如果排列的顺序对你很重要的话,可以额外添加排序条件,例如id字段是唯一的,可以考虑在排序字段中额外加个id去确保顺序稳定。

      我的方案: 排序条件改为 ORDER BY sas.score DESC,sas.statistics_point_id。statistics_point_id是该表的主键,问题解决了。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值