按两列排序 MySQL 表

2021-11-20 00:00:00 mysql sql-order-by

如何按两列对 MySQL 表进行排序?

我想要的是先按最高评分排序的文章,然后是最近的日期.例如,这将是一个示例输出(左# 是评分,然后是文章标题,然后是文章日期)

<前>+================+================================================+|article_rating |文章 |article_time |+================+================================================+|50 |这篇文章岩石|2009 年 2 月 4 日 |+----------------+------------------------------+---------------+|35 |这篇文章不错|2009 年 2 月 1 日 |+----------------+------------------------------+---------------+|5 |这篇文章不是那么热 |2009 年 1 月 25 日 |+================+================================================+

我使用的相关 SQL 是:

ORDER BY article_rating, article_time DESC

我可以按其中一个排序,但不能同时排序.

解决方案

默认排序是升序,需要在两个订单中添加关键字DESC:

ORDER BY article_rating DESC, article_time DESC

How do I sort a MySQL table by two columns?

What I want are articles sorted by highest ratings first, then most recent date. As an example, this would be a sample output (left # is the rating, then the article title, then the article date)

+================+=============================+==============+
| article_rating | article                     | article_time |
+================+=============================+==============+
| 50             | This article rocks          | Feb 4, 2009  |
+----------------+-----------------------------+--------------+
| 35             | This article is pretty good | Feb 1, 2009  |
+----------------+-----------------------------+--------------+
| 5              | This Article isn't so hot   | Jan 25, 2009 |
+================+=============================+==============+

The relevant SQL I'm using is:

ORDER BY article_rating, article_time DESC

I can sort by one or the other, but not both.

解决方案

Default sorting is ascending, you need to add the keyword DESC to both your orders:

ORDER BY article_rating DESC, article_time DESC

相关文章