ORDER BY <字段名> [ASC|DESC]
语法说明如下。ASC
表示字段按升序排序;DESC
表示字段按降序排序。其中ASC
为默认值。mysql> SELECT * FROM tb_students_info ORDER BY height; +----+--------+---------+------+------+--------+------------+ | id | name | dept_id | age | sex | height | login_date | +----+--------+---------+------+------+--------+------------+ | 2 | Green | 3 | 23 | F | 158 | 2016-10-22 | | 1 | Dany | 1 | 25 | F | 160 | 2015-09-10 | | 4 | Jane | 1 | 22 | F | 162 | 2016-12-20 | | 7 | Lily | 6 | 22 | F | 165 | 2016-02-26 | | 10 | Tom | 4 | 23 | M | 165 | 2016-08-05 | | 8 | Susan | 4 | 23 | F | 170 | 2015-10-01 | | 6 | John | 2 | 21 | M | 172 | 2015-11-11 | | 5 | Jim | 1 | 24 | M | 175 | 2016-01-15 | | 9 | Thomas | 3 | 22 | M | 178 | 2016-06-07 | | 3 | Henry | 2 | 23 | M | 185 | 2015-05-31 | +----+--------+---------+------+------+--------+------------+ 10 rows in set (0.08 sec)由结果可以看到,MySQL 对查询的 height 字段的数据按数值的大小进行了升序排序。
mysql> SELECT name,height FROM tb_students_info ORDER BY height,name; +--------+--------+ | name | height | +--------+--------+ | Green | 158 | | Dany | 160 | | Jane | 162 | | Lily | 165 | | Tom | 165 | | Susan | 170 | | John | 172 | | Jim | 175 | | Thomas | 178 | | Henry | 185 | +--------+--------+ 10 rows in set (0.09 sec)注意:在对多个字段进行排序时,排序的第一个字段必须有相同的值,才会对第二个字段进行排序。如果第一个字段数据中所有的值都是唯一的,MySQL 将不再对第二个字段进行排序。
mysql> SELECT name,height FROM tb_student_info ORDER BY height DESC,name ASC; +--------+--------+ | name | height | +--------+--------+ | Henry | 185 | | Thomas | 178 | | Jim | 175 | | John | 172 | | Susan | 170 | | Lily | 165 | | Tom | 165 | | Jane | 162 | | Dany | 160 | | Green | 158 | +--------+--------+ 10 rows in set (0.00 sec)DESC 关键字只对前面的列进行降序排列,在这里只对 height 字段进行降序。因此,height 按降序排序,而 name 仍按升序排序。如果想在多个列上进行降序排序,必须对每个列指定 DESC 关键字。
本文链接:http://task.lmcjl.com/news/16416.html