mysql - How "ORDER BY" ordered if there are same value?
问题描述
Let's say there's table:
name | score
A 100
B 98
C 99
D 99
E 99
F 98
and request sql = 'select * from table order by score desc'
I know order's gonna be 100, 99, 99, 99, 98, 98 but there are several values in 99 and 98.
I'm using MyIsam and want to make sure the order in the 99 and 98 is not changed even though I delete some element. For example, if the order was C->D->E and I delete D, then I expect to be C->E but no E->C. Is there any logic it works when there's same order value?
解决方案
SQL 表表示无序集。order by
因此,当键具有相同的值时,没有“默认”排序。
从技术上讲,这意味着 SQL 中的排序是不稳定的。解决方法是添加一个或多个附加键,以便每个组合都是唯一的。
对于您的示例数据,这大概可以使用以下方法处理name
:
order by score desc, name
如果可用,您还可以使用唯一标识每一行的任何其他列。这些键在score
.
推荐阅读
- python-3.x - 为什么不满足验证器条件时 wtforms 不生成错误?
- flutter - 如何从资产上传图片?
- android - 我可以通过应用内购买交易 ID 识别用户吗?
- php - Laravel 查询中的空数据
- regex - 如果管道输出中的任何行以带有 Where-Object 的 powershell 中的某个字符开头,则匹配
- python - 如何在streamlit中添加提交按钮(按钮内的按钮似乎重置了整个应用程序。为什么?)
- javascript - 某些浏览器上的 Recaptcha 超时
- django - 一对多通用列表视图 Django
- c# - Xamarin 形成 ViewModels 继承
- android - 如何在数组中上传多个图像 URL 字符串