2014-04-01 291 views
0

我使用以下查詢來返回按日期時間字段排序的行。MYSQL按日期時間順序排序而不是按時間順序排列

SELECT DISTINCT firstname, surname, email, DATE_FORMAT(dateregistered,'%y %b %d') AS dateregistered FROM clients, registrations, courses 
WHERE clients.id = registrations.clientid 
ORDER BY dateregistered 

但它返回

13 Nov 05 

14 Apr 01 

14 Feb 25 

14 Mar 01 

代替:

13 Nov 05 
14 Feb 25 
14 Mar 01 
14 Apr 01 

這似乎是基於每月按字母順序排序。

我怎樣才能得到它在實際日期訂購?

回答

1

SELECT子句中使用不同的投影:

... DATE_FORMAT(dateregistered,'%y %b %d') AS formattedDateRegistered 

因爲你鑄造列的列相同的名稱作爲自己的困惑的MySQL。

所以最終的查詢可以是:

SELECT DISTINCT firstname, surname, email, 
DATE_FORMAT(dateregistered,'%y %b %d') AS formattedDateregistered 
FROM clients, registrations, courses 
WHERE clients.id = registrations.clientid 
ORDER BY dateregistered 
0

的問題是,你必須重新格式化該日期列,並給它相同的名稱。爲了解決這個問題,在order by clause使用一個表的別名:我澄清

SELECT DISTINCT firstname, surname, email, 
     DATE_FORMAT(dateregistered,'%y %b %d') AS dateregistered 
FROM clients c join 
    registrations r 
    on c.id = r.clientid cross join 
    courses 
ORDER BY r.dateregistered; 

通知的查詢加入的。這個結構很奇怪。我想你錯過了courses的加入條件。

相關問題