2012-09-17 85 views
4

與多階選擇,所以我得到這個表:的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  | 
+----+---------------------+-----+----------------+ 

我想選擇所有的密鑰,但:

  • 通過時ASC與關閉= 0應該是爲了鑰匙,他們應該是 顯示的第一
  • 鍵與關= 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

+1

什麼是錯誤? – wroniasty

+0

有沒有錯誤它只是命令everthing通過'當'ASC – borewik

回答

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 
+0

是的!你真棒 :) – borewik

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

它幾乎沒問題,但它顯示第一行off = 1,比在表結束時off = 0我試圖修改它,但仍然可以這樣做... – borewik

+0

@borewik嘗試交換它們 –

2

試試這個:

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

我認爲,當是一個關鍵字,必須加引號。

+0

在第一個查詢中有一個'order by'。我剛剛檢查,它工作正常。 – wroniasty

+0

我試過了,它幾乎沒問題。但是,off = 1的部分的排序與off = 0 – borewik

+0

相同,這很奇怪,'when'列的類型是什麼? – wroniasty