【问题标题】:MySQL order by field plus fieldMySQL按字段加字段排序
【发布时间】:2012-02-08 12:26:58
【问题描述】:

我有一张桌子

id   type       left    right 
1    featured   1       2 
2    default    3       1 
3    default    5       2 
4    default    2       7 
5    featured   3       4 
6    featured   3       2 
7    day        1       3
8    default    12      42

我需要输出五个 id 其中type != day 并按sum(left + right) 排序并按特征排序,默认

首先,需要ORDERING by sum(left + right)的所有特色类型,而不是type = dafule ordering by sum(left + right) LIMIT 5

我想得到什么:

5, 6, 1, 8, 4

谢谢!

【问题讨论】:

  • 您是否特别希望将结果作为按顺序限定的单个 ID 字符串,或者结果集或行是否正常。我了解退货集的顺序基础。

标签: mysql sorting field


【解决方案1】:

首先按“Featured”排序是排序中的 IF()... 如果类型是“featured”,则使用 1 作为排序基础,否则使用 2。因为您只有精选和默认可用(限制“天”条目)。否则,将更改为 CASE/WHEN 构造以考虑其他类型

select
      yt.id,
      yt.type,
      yt.left + yt.right as LeftPlusRight
   from 
      YourTable yt
   where
      yt.type <> 'day'
   order by
      if( yt.type = 'featured', 1, 2 ),
      LeftPlusRight  DESC
   limit 5

【讨论】:

    【解决方案2】:

    预期结果:

    5、6、1、8、4

    您实际上希望按type desc 对 id 进行排序,然后按 sum of leftright desc 对 id 进行排序,因此以下查询可能满足您的需求:

    SELECT
        id
    FROM
        tlr
    WHERE
        `type`!='day'
    ORDER BY 
        `type` DESC, `left`+`right` DESC
    LIMIT 5;
    

    它是这样工作的:

    mysql [localhost] {msandbox} (test) > select * from tlr;
    +----+----------+------+-------+
    | id | type     | left | right |
    +----+----------+------+-------+
    |  1 | featured |    1 |     2 |
    |  2 | default  |    3 |     1 |
    |  3 | default  |    5 |     2 |
    |  4 | default  |    2 |     7 |
    |  5 | featured |    3 |     4 |
    |  6 | featured |    3 |     2 |
    |  7 | day      |    1 |     3 |
    |  8 | default  |   12 |    42 |
    +----+----------+------+-------+
    8 rows in set (0.00 sec)
    
    mysql [localhost] {msandbox} (test) > select id from tlr where `type`!='day' order by type desc, `left`+`right` desc limit 5;
    +----+
    | id |
    +----+
    |  5 |
    |  6 |
    |  1 |
    |  8 |
    |  4 |
    +----+
    5 rows in set (0.00 sec)
    

    【讨论】:

      【解决方案3】:
      select id
      from your_table
      where `type` != 'day'
      order by `type`, sum(left + right)
      group by `type`    
      limit 5
      

      【讨论】:

        【解决方案4】:
        SELECT 
             ID
        FROM 
             yourTable
        WHERE 
             type <> 'day'
        ORDER BY (type = 'featured') DESC, (`left` + `right`) DESC
        LIMIT 5
        

        上面的查询给出了我认为正确的结果。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-11-08
          • 1970-01-01
          • 1970-01-01
          • 2011-07-01
          • 2015-06-21
          • 2013-07-10
          • 2013-05-05
          相关资源
          最近更新 更多