mysql> SELECT name, birth FROM mytable ORDER BY birth; +----------+------------+ | name | birth | +----------+------------+ | tom | 1973-09-02 | | abccs | 1977-07-07 | | mary | 1978-12-12 | +----------+------------+ 3 row in set (0.00 sec) |
我们可以用DESC来进行逆序排序:
mysql> SELECT name, birth FROM mytable ORDER BY birth DESC; +----------+------------+ | name | birth | +----------+------------+ | mary | 1978-12-12 | | abccs | 1977-07-07 | | tom | 1973-09-02 | +----------+------------+ 3 row in set (0.00 sec) |
7、 行计数
数据库经常要统计一些数据,如表中员工的数目,我们就要用到行计数函数COUNT()。COUNT()函数用于对非NULL结果的记录进行计数:
mysql> SELECT COUNT(*) FROM mytable; +----------+ | COUNT(*) | +----------+ | 3 | +----------+ 1 row in set (0.06 sec) 员工中男女数量: mysql> SELECT sex, COUNT(*) FROM mytable GROUP BY sex; +------+----------+ | sex | COUNT(*) | +------+----------+ | f | 2 | | m | 1 | +------+----------+ 2 row in set (0.00 sec) |
注意我们使用了GROUP BY对SEX进行了分组。