您可能已经注意到前面的例子中,结果行没有特定的顺序显示。当以某种有意义的方式对行进行排序时,通常更容易检查查询输出。若要对结果排序,请使用order by子句

    下面是动物生日,按日期排序:

    1. mysql> SELECT name, birth FROM pet ORDER BY birth;
    2. +----------+------------+
    3. | name | birth |
    4. +----------+------------+
    5. | Buffy | 1989-05-13 |
    6. | Bowser | 1989-08-31 |
    7. | Fang | 1990-08-27 |
    8. | Fluffy | 1993-02-04 |
    9. | Claws | 1994-03-17 |
    10. | Slim | 1996-04-29 |
    11. | Whistler | 1997-12-09 |
    12. | Chirpy | 1998-09-11 |
    13. | Puffball | 1999-03-30 |
    14. +----------+------------+

    默认排序顺序是升序,第一个值最小。如果要以反向(降序)顺序进行排序,在您要排序的列的名称后添加desc

    mysql> SELECT name, birth FROM pet ORDER BY birth DESC;
    +----------+------------+
    | name     | birth      |
    +----------+------------+
    | Puffball | 1999-03-30 |
    | Chirpy   | 1998-09-11 |
    | Whistler | 1997-12-09 |
    | Slim     | 1996-04-29 |
    | Claws    | 1994-03-17 |
    | Fluffy   | 1993-02-04 |
    | Fang     | 1990-08-27 |
    | Bowser   | 1989-08-31 |
    | Buffy    | 1989-05-13 |
    +----------+------------+
    

    可以在多个列上排序,也可以按不同的方向对不同的列进行排序。例如,按升序排序动物类型,然后按降序降序排列动物类型(最年幼的动物优先),使用下面的查询: 结果通常以order by后跟的那一字段决定,如果species一样,则按birth进行排序。

    mysql> SELECT name, species, birth FROM pet
        -> ORDER BY species, birth DESC;
    +----------+---------+------------+
    | name     | species | birth      |
    +----------+---------+------------+
    | Chirpy   | bird    | 1998-09-11 |
    | Whistler | bird    | 1997-12-09 |
    | Claws    | cat     | 1994-03-17 |
    | Fluffy   | cat     | 1993-02-04 |
    | Fang     | dog     | 1990-08-27 |
    | Bowser   | dog     | 1989-08-31 |
    | Buffy    | dog     | 1989-05-13 |
    | Puffball | hamster | 1999-03-30 |
    | Slim     | snake   | 1996-04-29 |
    +----------+---------+------------+
    

    DESC关键字仅适用于前一列的名字(出生);它不影响物种的列的排序顺序。