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

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

+================+=============================+==============+
| 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 |
+================+=============================+==============+

我使用的相关SQL是:

ORDER BY article_rating, article_time DESC

我可以按一个或另一个排序,但不能同时排序。


默认排序是升序的,你需要添加关键字DESC到你的订单:

ORDER BY article_rating DESC, article_time DESC
ORDER BY article_rating ASC , article_time DESC

结尾的DESC将按两列降序排序。如果不需要ASC,则必须指定ASC

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.

这可能会帮助那些正在寻找两列排序表的方法的人,但在平行的方式。这意味着使用聚合排序函数组合两个排序。这是非常有用的,例如,检索文章使用全文搜索,也涉及文章的发表日期。

这只是一个例子,但是如果您了解其中的思想,您可以找到许多可以使用的聚合函数。您甚至可以对列进行加权,使其更倾向于一秒。我的函数在这两种排序中都采取了极端的方式,因此值最高的行都在上面。

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

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