MySQL选择多个顺序

时间:2012-09-17 15:19:26

标签: mysql

所以我得到了这张桌子:

+----+---------------------+-----+----------------+
| ID | WHEN                | OFF | (other..stuff) |
+----+---------------------+-----+----------------+
| 1  | 2012-09-17 17:00:00 | 0   | anything1      |
| 2  | 2012-09-17 18:00:00 | 0   | anything2      |
| 3  | 2012-08-31 21:00:00 | 1   | blabla321      |
| 4  | 2012-08-31 18:30:00 | 1   | blab32121      |
+----+---------------------+-----+----------------+

我想选择所有键,但是:

  • off = 0的键应该在ASC时排序,它们应该是 首先显示
  • off = 1的键应该在DESC时按顺序排列,它们应该是 在(最后)
  • 之后显示

我试过这样的事情:

(SELECT * FROM `table` WHERE `off` = 0 ORDER BY `when` ASC)
UNION
(SELECT * FROM `table` WHERE `off` = 1 ORDER BY `when` DESC)

但它不起作用。

同时检查: http://i.imgur.com/81Hzq.jpg

3 个答案:

答案 0 :(得分:2)

试试这个:

(SELECT * FROM table WHERE off = 0 ORDER BY `when` ASC) 
UNION 
(SELECT * FROM table WHERE off = 1 ORDER BY `when` DESC);

我认为WHEN是一个关键字,必须引用。

答案 1 :(得分:1)

SELECT * 
FROM table 
ORDER BY CASE WHEN off = 0 THEN `when` END ASC,
         CASE WHEN off = 1 THEN `when` END DESC 

答案 2 :(得分:1)

select *
from `table`
order by `off`,
    case `off`
        when 0 then timestampdiff(second, current_timestamp, `when`)
        when 1 then timestampdiff(second, `when`, current_timestamp)
    end