2012-02-08 58 views
0

我有一個表MySQL的ORDER BY場加場

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 

我需要輸出5個id其中type != daysum(left + right)排序並通過功能排序,默認

首先,需要各方面的功能類型ORDERING by sum(left + right),比type = dafule ordering by sum(left + right) LIMIT 5

我想什麼:

5, 6, 1, 8, 4 

謝謝!

+1

您是否希望將結果作爲單個字符串的ID排序,或者結果集或行是否正確。我明白回報集的順序依據。 – DRapp 2012-02-08 12:51:20

回答

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 
0
select id 
from your_table 
where `type` != 'day' 
order by `type`, sum(left + right) 
group by `type`  
limit 5 
0
SELECT 
    ID 
FROM 
    yourTable 
WHERE 
    type <> 'day' 
ORDER BY (type = 'featured') DESC, (`left` + `right`) DESC 
LIMIT 5 

上述查詢給你正確的結果,我認爲。

1

與預期結果:

5,6,1,8,4

你真正想要的ID通過 type遞減由 left sumright降序排序,然後

,所以以下查詢可滿足您的需求:

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)