MySQL日期格式

时间:2011-06-08 14:18:56

标签: mysql datetime

我有以下MySQL。

    SELECT
        `outputtable`.`date`,
        count(*) as `count`
    FROM (
        SELECT
            CONCAT(DATE(`mytable`.`starttime`),' ',HOUR(`mytable`.`starttime`),':',LPAD(10*(MINUTE(`mytable`.`starttime`) DIV 10),2,'0')) as `date`,
            `mytable`.`clientid`
        FROM
            `mytable`
        WHERE
            `mytable`.`clientid`='1'
        GROUP BY
            `mytable`.`clientid`
        ORDER BY 
            `date`
        ) AS outputtable
    GROUP BY
        `date`
    ORDER BY
        `date` ASC

根据日期时间排序规则,输出的日期字段未正确排序。

如何订购输出的示例:

2011-02-01 17:00 | 4

2011-02-01 18:00 | 1

2011-02-01 19:00 | 1

2011-02-01 21:00 | 1

2011-02-01 8:00 | 6

2011-02-01 9:00 | 7

我认为这是因为名为'date'的新创建的字段是varchar。

如何在'outputtable'表中将字段'date'的类型设置为'Datetime',以便正确排序?

提前致谢,

小时。

2 个答案:

答案 0 :(得分:2)

只需使用日期时间作为列类型:D

答案 1 :(得分:1)

将它投射到日期,如下所示:

cast(CONCAT(DATE(`mytable`.`starttime`),' ',HOUR(`mytable`.`starttime`),':',LPAD(10*(MINUTE(`mytable`.`starttime`) DIV 10),2,'0')) as DATE) as date

或更可读:

 SELECT
    cast(`outputtable`.`date` as date),
    count(*) as `count`
 -- the rest of the query the same