日期字段在sql中没有正确排序

时间:2012-09-14 11:07:36

标签: mysql

以下是我的搜索结果(by cruise_date):

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

3 个答案:

答案 0 :(得分:4)

现在,它会对DATE_FORMAT(cruise_date, '%c/%e/%Y')的结果进行文本排序,而不是对字段cruise_date进行排序。试试ORDER BY cruise.cruise_date

答案 1 :(得分:3)

这是因为您在SELECT子句中使用了相同的别名。您需要将别名更改为不同的名称或在cruise.cruise_date子句中使用ORDER BY,否则记录将从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

答案 2 :(得分:1)

或者,尝试在days_till_cruise

上订购
ORDER BY
       `days_till_cruise`