MySQL Order By排序混乱问题

问题描述

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

MySQL Order By排序混乱问题

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

MySQL Order By排序混乱问题

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

MySQL Order By排序混乱问题MySQL Order By排序混乱问题

       结果确实乱序了。

查找解决方案

       查找原因,发现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是该表的主键,问题解决了。