MySQL按字段加字段排序

时间:2012-02-08 12:26:58

标签: mysql sorting field

我有一张桌子

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

我需要在type != day输出五个ID并按sum(left + right)对其进行排序,然后按特色排序,默认

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

我想得到什么:

5, 6, 1, 8, 4

谢谢!

4 个答案:

答案 0 :(得分:2)

首先出现的“精选”排序是按顺序排列的IF()如果类型为“精选”,则使用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

答案 1 :(得分:1)

预期结果:

  

5,6,1,8,4

您实际上想要按type desc,然后sum 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)

答案 2 :(得分:0)

select id
from your_table
where `type` != 'day'
order by `type`, sum(left + right)
group by `type`    
limit 5

答案 3 :(得分:0)

SELECT 
     ID
FROM 
     yourTable
WHERE 
     type <> 'day'
ORDER BY (type = 'featured') DESC, (`left` + `right`) DESC
LIMIT 5

以上查询为您提供了正确的结果。