278

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

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

+================+==============================+== =============+
| article_rating | 文章 | 文章时间 |
+================+==============================+== =============+
| 50 | 这篇文章震撼 | 2009 年 2 月 4 日 |
+----------------+-----------------------------+-- ------------+
| 35 | 这篇文章不错| 2009 年 2 月 1 日 |
+----------------+-----------------------------+-- ------------+
| 5 | 这篇文章不那么热了| 2009 年 1 月 25 日 |
+================+==============================+== =============+

我正在使用的相关 SQL 是:

ORDER BY article_rating, article_time DESC

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

4

5 回答 5

573

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

ORDER BY article_rating DESC, article_time DESC
于 2009-02-05T07:51:35.883 回答
41
ORDER BY article_rating, article_time DESC

仅当有两篇具有相同评分的文章时才会按 article_time 排序。从我在你的例子中可以看到,这正是发生的事情。

↓ primary sort                         secondary sort ↓
1.  50 | This article rocks          | Feb 4, 2009    3.
2.  35 | This article is pretty good | Feb 1, 2009    2.
3.  5  | This Article isn't so hot   | Jan 25, 2009   1.

但考虑:

↓ primary sort                         secondary sort ↓
1.  50 | This article rocks          | Feb 2, 2009    3.
1.  50 | This article rocks, too     | Feb 4, 2009    4.
2.  35 | This article is pretty good | Feb 1, 2009    2.
3.  5  | This Article isn't so hot   | Jan 25, 2009   1.
于 2009-02-05T07:55:05.580 回答
18
ORDER BY article_rating ASC , article_time DESC

DESC最后将按两列降序排序。您必须指定ASC是否要否则

于 2009-02-05T07:54:07.330 回答
8

这可能会帮助那些正在寻找按两列但以并行方式对表格进行排序的方法的人。这意味着使用聚合排序功能组合两种排序。例如,在使用全文搜索检索文章以及涉及文章发布日期时,它非常有用。

这只是一个例子,但如果你抓住了这个想法,你会发现很多聚合函数可以使用。您甚至可以对列进行加权,使其更喜欢一秒。我的函数在这两种情况下都取了极端,因此最有价值的行位于顶部。

抱歉,如果有更简单的解决方案来完成这项工作,但我没有找到任何解决方案。

SELECT
 `id`,
 `text`,
 `date`
 FROM
   (
   SELECT
     k.`id`,
     k.`text`,
     k.`date`,
     k.`match_order_id`,
     @row := @row + 1 as `date_order_id`
     FROM
     (
       SELECT
         t.`id`,
         t.`text`,
         t.`date`,
         @row := @row + 1 as `match_order_id`
         FROM
         (
           SELECT
             `art_id` AS `id`,
             `text`   AS `text`,
             `date`   AS `date`,
             MATCH (`text`) AGAINST (:string) AS `match`
             FROM int_art_fulltext
             WHERE MATCH (`text`) AGAINST (:string IN BOOLEAN MODE)
             LIMIT 0,101
         ) t,
         (
           SELECT @row := 0
         ) r
         ORDER BY `match` DESC
     ) k,
     (
       SELECT @row := 0
     ) l
     ORDER BY k.`date` DESC
   ) s
 ORDER BY (1/`match_order_id`+1/`date_order_id`) DESC
于 2012-04-20T09:19:12.103 回答
6

以下将根据两列按降序排列您的数据。

ORDER BY article_rating DESC, article_time DESC
于 2013-09-29T04:15:53.583 回答