2016-06-13 80 views
1

user結構:mysql命令由兩個unixtime列組合在一起

id(PK)(int) 
name(varchar) 
time1(int10) unixtime 
time2(int10) unixtime 

SELECT * FROM `user` ORDER BY `time1` DESC,`time2` DESC 


+------------------------------------------------------+ 
| id  | name |  time1  |  time2  | 
+------------------------------------------------------+ 
| 12345  | Joe | 1405605785 | 1406733506 | 
| 12346  | John | 1406733506 |     | 
| 12347  | David |    | 1405684190 | 
+------------------------------------------------------+ 

我使用這個SQL語句:

SELECT * FROM `user` ORDER BY `time1` DESC,`time2` DESC 

如何兩列的時間相結合,分類說明?

============

爲鷺

更多例子回覆

+------------------------------------------------------+ 
| id  | name |  time1  |  time2  | 
+------------------------------------------------------+ 
| 12345  | Joe | 1   | 2    | 
| 12346  | John | 5   |     | 
| 12347  | David |    | 4    | 
+------------------------------------------------------+ 

我想有點像那個(DESC)

John (time = 5) 
David (time = 4) 
Joe (time max value = 2) 
+1

什麼是您預期的結果? – Blank

+2

'SELECT * FROM user ORDER BY coalesce(time1,time2)DESC' –

+0

感謝juergen,但結果仍然像ORDER BY time1 DESC,time2 DESC – Sky

回答

1

這是所謂的條件排序使用CASE EXPRESSION

SELECT * FROM `user` t 
ORDER BY CASE WHEN t.time1 is null THEN t.time2 ELSE t.time1 END DESC 

也可以寫爲:

ORDER BY coalesce(t.time1,t.time2) 

你沒有提供任何預期的結果,而你沒說由列的結果應該在的情況下,責令兩time1,time2NULL,所以我估計你希望它由第一列排序。如果不是這種情況,請用time2替換time1

試試這個:

ORDER BY GREATEST(t.time1,t.time2) DESC 
+0

謝謝,但結果仍然像ORDER BY 'time1' DESC,'time2' DESC – Sky

+0

你想如何訂購? @Sky – sagi

+0

我編輯了我的主題內容。 :) – Sky