首页 文章

按两列排序MySQL表

提问于
浏览
182

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

我想要的是按最高评分排序的文章,然后是最近的日期 . 作为一个例子,这将是一个示例输出(左#是评级,然后是文章 Headers ,然后是文章日期)

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

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

5 回答

  • 9

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

    ORDER BY article_rating DESC, article_time DESC
    
  • 25
    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.
    
  • 393
    ORDER BY article_rating ASC , article_time DESC
    

    最后 DESC 将按两列降序排序 . 如果需要,您必须指定 ASC

  • 7

    这可能有助于那些正在寻找通过两列排序表的方式的人,但是以相似的方式 . 这意味着使用聚合排序功能组合两种排序 . 例如,在使用全文搜索检索文章以及文章发布日期时,它非常有用 .

    这只是一个例子,但是如果你理解了这个想法,你可以找到很多要使用的聚合函数 . 您甚至可以对列进行加权,使其优先于一秒钟 . 我的功能从两种类型中都是极端的,因此最有 Value 的行位于顶部 .

    对不起,如果存在更简单的解决方案来完成这项工作,但我还没有找到 .

    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
    
  • 3

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

    ORDER BY article_rating DESC, article_time DESC
    

相关问题