2012-09-14 52 views
4

正確排序這裏是我的搜索結果(通過cruise_date):日期字段在SQL

CRUISE_DATE  DAYS_TILL_CRUISE NAME 
10/13/2012 29 Octobertfest 
10/20/2012 36 Rare Air Show, 
10/20/2012 36 Bugs and Bratz 
11/10/2012 57 Fall Color Super Cruise 
11/10/2012 57 Club Cruise-In to Desoto State Park 
9/22/2012 8 Bugs on the Bayou 
9/23/2012 9 Hot Dogs and Hot Rods 

注意的日期去十月,十一月,九月。 這是我的SQL語句:

SELECT 
     DATE_FORMAT(cruise_date, '%c/%e/%Y') AS cruise_date, 
     DATEDIFF(cruise_date, CURDATE()) AS days_till_cruise, 
     NAME 
FROM 
     `cruise` 
WHERE 
     `cruise_date` >= '2012-09-14' 
ORDER BY 

     `cruise_date` 

爲什麼我的日期排序是否正確?

Click here to see this in action

回答

4

它現在對DATE_FORMAT(cruise_date, '%c/%e/%Y')的結果進行了文本排序,而不是字段cruise_date。試試ORDER BY cruise.cruise_date

3

這是因爲您在SELECT子句中使用了相同的別名。您需要將別名更改爲不同的內容,或者在ORDER BY子句中使用cruise.cruise_date,否則記錄將從select中的文本列進行排序。試試這個:或者

SELECT 
     DATE_FORMAT(cruise_date, '%c/%e/%Y') AS cruise_date_1, 
     DATEDIFF(cruise_date, CURDATE()) AS days_till_cruise, 
     NAME 
FROM 
     `cruise` 
WHERE 
     `cruise_date` >= '2012-09-14' 
ORDER BY 

     `cruise_date` 

SQLFiddle Demo

+0

SQLFiddle NICE! –

1

,嘗試訂購它days_till_cruise

ORDER BY 
     `days_till_cruise`