我们知道从 MySQL 表中使用 SQL SELECT 语句来读取数据。
如果我们需要对读取的数据进行排序,我们就可以使用 MySQL 的 ORDER BY 子句来设定你想按哪个字段哪种方式来进行排序,再返回搜索结果。

语法

以下是 SQL SELECT 语句使用 ORDER BY 子句将查询数据排序后再返回数据:

  1. mysql> select * from nowcoder_tbl order by submission_date asc;
  2. +-------------+----------------+-----------------+-----------------+
  3. | nowcoder_id | nowcoder_title | nowcoder_author | submission_date |
  4. +-------------+----------------+-----------------+-----------------+
  5. | 3 | JAVA 教程 | NOWCODER.COM | 2019-10-06 |
  6. | 4 | 学习 Python | NOWCODER.COM | 2019-10-06 |
  7. | 1 | 学习 PHP | 牛客教程 | 2019-10-10 |
  8. | 2 | 学习 MySQL | 牛客教程 | 2019-10-10 |
  9. +-------------+----------------+-----------------+-----------------+
  10. 4 rows in set (0.00 sec)
  11. mysql> select * from nowcoder_tbl order by submission_date desc;
  12. +-------------+----------------+-----------------+-----------------+
  13. | nowcoder_id | nowcoder_title | nowcoder_author | submission_date |
  14. +-------------+----------------+-----------------+-----------------+
  15. | 1 | 学习 PHP | 牛客教程 | 2019-10-10 |
  16. | 2 | 学习 MySQL | 牛客教程 | 2019-10-10 |
  17. | 3 | JAVA 教程 | NOWCODER.COM | 2019-10-06 |
  18. | 4 | 学习 Python | NOWCODER.COM | 2019-10-06 |
  19. +-------------+----------------+-----------------+-----------------+
  20. 4 rows in set (0.00 sec)

原文有PHP脚本实列:https://www.nowcoder.com/tutorial/10006/77339659c9284dfbbbc006ef09686938