简体   繁体   English

mysql按多列顺序排序

[英]mysql order by multiple columns different directions

I have table. 我有桌子。

Table structure is 表结构是

在此处输入图片说明

And now I run the query 现在我运行查询

SELECT * FROM `studentregistrations`
ORDER BY `studentregistrations`.`studentID`  DESC, `studentregistrations`.`studentName`

And the result I am getting is 我得到的结果是

在此处输入图片说明

I want an explanation how it is working. 我想解释一下它是如何工作的。 Because I am confusing that it should give result like studentID is in descending order and studentName is in ascending order. 因为让我感到困惑,它应该给出结果,例如studentID为降序, studentName为升序。

I checked below answer but not getting any proper explanations 我检查了以下答案,但未得到任何适当的解释

mysql query order by multiple items MySQL查询顺序由多个项目

PHP MySQL Order by Two Columns PHP MySQL按两列排序

I think your expectations are that the columns are sorted independently, so that all student names are in alphabetic order and all student ids are in descending order, independently on the names. 我认为您的期望是,列是独立排序的,因此所有学生姓名均按字母顺序排列,所有学生ID均按降序排列,而与姓名无关。 If that would happen, you would get results where a student id is next to the wrong name, so fortunately that doesn't happen. 如果发生这种情况,您将得到错误的名称旁边的学生证的结果,因此幸运的是不会发生。

Instead, it sorts by the first column first and then by the next column. 而是按第一列排序,然后按下一列排序。 The secondary sort only applies to groups that have the same value in the first column. 次要排序仅适用于第一列中具有相同值的组。

So if you would have 10 students with the same ID, then for that ID their names would be alphabetically sorted. 因此,如果您有10个具有相同ID的学生,则对于该ID,他们的姓名将按字母顺序排序。 But since the ID is unique, the secondary sorting is useless. 但是,由于ID是唯一的,因此二级排序是无用的。

It would be useful, for example, to use 例如,使用

ORDER BY UniversityId, StudentName

That way, you would have a list where all students of the same university are grouped together, and within these groups they are sorted alphabetically by name. 这样,您将获得一个列表,其中将同一所大学的所有学生分组在一起,并且在这些组中,他们按名称的字母顺序进行排序。

When you sort using multiple columns, the order of the second column only influences the order when two or more values are equal in the first column. 当您使用多列进行排序时,第二列的顺序只会影响第一列中两个或多个值相等时的顺序。 If all values in the first column are unique, the other order columns do not matter. 如果第一列中的所有值都是唯一的,则其他顺序列无关紧要。

Your query first orders by student id, and then following that, orders any 'ties' by student name. 您所查询的第一批订单的学生证,然后紧接着,命令把任何“关系”的学生姓名。

It's impossible to have both of your order by's honoured in full, because then there would be row/column mismatches. 不可能完全履行您的两个订单,因为这样会出现行/列不匹配的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM