2/7 SELECT语句:排序(ORDER BY)

序号 说明 操作
1 排序数据 ORDER BY
2 按多个列排序 ,分隔
3 指定排序方向 降序:DESC 升序(默认):ASC
4 ORDER BY结合LIMIT 顺序:FROMORDER BYLIMIT

以下为数据库SQLTEST中的三张表,其结构和内容如下:
2/7 SELECT语句:排序(ORDER BY)_第1张图片

1.排序数据

ORDER BY子句取一个或多个列的名字,据此对输出进行排序。

mysql> SELECT Stu_id, Lesson_id
    -> FROM t_score
    -> ORDER BY Lesson_id;
+--------+-----------+
| Stu_id | Lesson_id |
+--------+-----------+
|      1 | L001      |
|      2 | L001      |
|      1 | L002      |
|      3 | L003      |
|      2 | L004      |
|      4 | L005      |
+--------+-----------+

通过非选择列进行排序是完全合法的。

mysql> SELECT Stu_id,Score
    -> FROM t_score
    -> ORDER BY Lesson_id;
+--------+-------+
| Stu_id | Score |
+--------+-------+
|      1 |    90 |
|      2 |    84 |
|      1 |    86 |
|      3 |    85 |
|      2 |    75 |
|      4 |    98 |
+--------+-------+

2.按多个列排序

只要指定列名,列名之间用逗号分开即可;
多个列排序时,排序完全按照所规定的的顺序进行。仅在多个行具有相同的Lesson_id值时才对分数按Score进行排序;如果Lesson_id列中所有的值是唯一的,则不会按Score排序。

mysql> SELECT Stu_id,Lesson_id,Score
    -> FROM t_score
    -> ORDER BY Lesson_id,Score;
+--------+-----------+-------+
| Stu_id | Lesson_id | Score |
+--------+-----------+-------+
|      2 | L001      |    84 |
|      1 | L001      |    90 |
|      1 | L002      |    86 |
|      3 | L003      |    85 |
|      2 | L004      |    75 |
|      4 | L005      |    98 |
+--------+-----------+-------+

3.指定排序方向

数据排序不限于升序排序(从A到Z),这只是默认的排序顺序。还可以使用ORDER BY子句以降序(从Z到A)顺序排序;
为了进行降序排序,必须指定DESC关键字。

mysql> SELECT Stu_id,Lesson_id,Score
    -> FROM t_score
    -> ORDER BY Score DESC;
+--------+-----------+-------+
| Stu_id | Lesson_id | Score |
+--------+-----------+-------+
|      4 | L005      |    98 |
|      1 | L001      |    90 |
|      1 | L002      |    86 |
|      3 | L003      |    85 |
|      2 | L001      |    84 |
|      2 | L004      |    75 |
+--------+-----------+-------+

对多个列进行降序排序:如果想在多个列上进行降序排序,必须对每个列指定DESC关键字;
依据Lesson_id值进行降序,再依据Score值进行默认(升序)排序。

mysql> SELECT Stu_id,Lesson_id,Score
    -> FROM t_score
    -> ORDER BY Lesson_id DESC,Score;
+--------+-----------+-------+
| Stu_id | Lesson_id | Score |
+--------+-----------+-------+
|      4 | L005      |    98 |
|      2 | L004      |    75 |
|      3 | L003      |    85 |
|      1 | L002      |    86 |
|      2 | L001      |    84 |
|      1 | L001      |    90 |
+--------+-----------+-------+

4.ORDER BY结合LIMIT

ORDER BY子句的位置:FROM—ORDER BY—LIMIT;
找出成绩最高的学生。

mysql> SELECT Stu_id,Lesson_id,Score
    -> FROM t_score
    -> ORDER BY Score DESC
    -> LIMIT 1;
+--------+-----------+-------+
| Stu_id | Lesson_id | Score |
+--------+-----------+-------+
|      4 | L005      |    98 |
+--------+-----------+-------+

你可能感兴趣的:(数据库)