为了以特定方式从结果集中的 MySQL 表中获取记录(升序或降序),我们需要使用 ORDER BY 子句以及 ASC 或 DESC 关键字。如果我们不使用任何上述关键字,那么 MySQL 默认按升序返回记录。 ORDER BY 子句返回基于特定字段(升序或降序)的结果集,我们将使用 ORDER BY 子句。假设我们要对下表的行进行排序 -
mysql> Select * from Student;
+--------+--------+--------+
| Name | RollNo | Grade |
+--------+--------+--------+
| Gaurav | 100 | B.tech |
| Aarav | 150 | M.SC |
| Aryan | 165 | M.tech |
+--------+--------+--------+
3 rows in set (0.00 sec)
下面的查询按“名称”按升序对表进行排序。
mysql> Select * from student order by name;
+--------+--------+--------+
| Name | RollNo | Grade |
+--------+--------+--------+
| Aarav | 150 | M.SC |
| Aryan | 165 | M.tech |
| Gaurav | 100 | B.tech |
+--------+--------+--------+
3 rows in set (0.00 sec)
下面的查询按“Grade in DESCENDING order”对表格进行排序。
mysql> Select * from student order by Grade DESC;
+--------+--------+--------+
| Name | RollNo | Grade |
+--------+--------+--------+
| Aryan | 165 | M.tech |
| Aarav | 150 | M.SC |
| Gaurav | 100 | B.tech |
+--------+--------+--------+
3 rows in set (0.00 sec)