- order by: 对所取得的数据按给定的字段今夕排序。
- 排序方式有:
正序 asc 倒序 desc 省略不写,默认 asc
可以单个排序 select * from test order by age asc; select * from test order by age desc; 也可以多个排序,根据情况去使用 select * from test order by age asc, name desc;
- 测试数据
mysql> select * from test; +----+------+------+ | id | name | age | +----+------+------+ | 1 | dzm | 20 | | 2 | xyq | 20 | | 3 | xyq | 20 | | 4 | djy | 5 | | 5 | NULL | NULL | +----+------+------+
``` mysql> select * from test order by age; +----+------+------+ | id | name | age | +----+------+------+ | 5 | NULL | NULL | | 4 | djy | 5 | | 1 | dzm | 20 | | 2 | xyq | 20 | | 3 | xyq | 20 | +----+------+------+ 5 rows in set (0.00 sec)
mysql> select * from test order by age asc; +----+------+------+ | id | name | age | +----+------+------+ | 5 | NULL | NULL | | 4 | djy | 5 | | 1 | dzm | 20 | | 2 | xyq | 20 | | 3 | xyq | 20 | +----+------+------+ 5 rows in set (0.00 sec)
mysql> select * from test order by age desc; +----+------+------+ | id | name | age | +----+------+------+ | 1 | dzm | 20 | | 2 | xyq | 20 | | 3 | xyq | 20 | | 4 | djy | 5 | | 5 | NULL | NULL | +----+------+------+ 5 rows in set (0.00 sec)
mysql> select * from test group by name; +----+------+------+ | id | name | age | +----+------+------+ | 5 | NULL | NULL | | 4 | djy | 5 | | 1 | dzm | 20 | | 2 | xyq | 20 | +----+------+------+ 4 rows in set (0.00 sec)
mysql> select * from test group by name order by age desc; +----+------+------+ | id | name | age | +----+------+------+ | 1 | dzm | 20 | | 2 | xyq | 20 | | 4 | djy | 5 | | 5 | NULL | NULL | +----+------+------+ 4 rows in set (0.00 sec) ```