You may have noticed in the preceding examples that the result rows are displayed in no particular order. 在前面的示例中,您可能已经注意到结果行没有按特定顺序显示。It is often easier to examine query output when the rows are sorted in some meaningful way. 当以某种有意义的方式对行进行排序时,通常更容易检查查询输出。To sort a result, use an 要对结果排序,请使用ORDER BY
clause.ORDER BY
子句。
Here are animal birthdays, sorted by date:以下是动物的生日,按日期排序:
mysql> SELECT name, birth FROM pet ORDER BY birth;
+----------+------------+
| name | birth |
+----------+------------+
| Buffy | 1989-05-13 |
| Bowser | 1989-08-31 |
| Fang | 1990-08-27 |
| Fluffy | 1993-02-04 |
| Claws | 1994-03-17 |
| Slim | 1996-04-29 |
| Whistler | 1997-12-09 |
| Chirpy | 1998-09-11 |
| Puffball | 1999-03-30 |
+----------+------------+
On character type columns, sorting—like all other comparison operations—is normally performed in a case-insensitive fashion. 在字符类型列上,排序与所有其他比较操作一样,通常以不区分大小写的方式执行。This means that the order is undefined for columns that are identical except for their case. 这意味着除了大小写之外,对于相同的列,顺序是未定义的。You can force a case-sensitive sort for a column by using 您可以使用BINARY
like so: ORDER BY BINARY
.col_name
BINARY
强制对列进行区分大小写的排序,如:ORDER BY BINARY
。col_name
The default sort order is ascending, with smallest values first. 默认排序顺序为升序,最小值优先。To sort in reverse (descending) order, add the 要按相反(降序)顺序排序,请将DESC
keyword to the name of the column you are sorting by: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 |
+----------+------------+
You can sort on multiple columns, and you can sort different columns in different directions. 您可以对多个列进行排序,也可以对不同方向的不同列进行排序。For example, to sort by type of animal in ascending order, then by birth date within animal type in descending order (youngest animals first), use the following query:例如,要按动物类型按升序排序,然后按动物类型内的出生日期按降序排序(首先是最年轻的动物),请使用以下查询:
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 | +----------+---------+------------+
The DESC
keyword applies only to the column name immediately preceding it (birth
); it does not affect the species
column sort order.DESC
关键字仅适用于紧靠其前面的列名(birth
);它不影响species
列排序顺序。