开发者

MySQL date formatting

I have the following 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

The outputted date field does not order correct开发者_StackOverflow中文版ly according to datetime ordering rules.

Example of how the output is ordered:

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

I presume that this is because the newly created field named 'date' is a varchar.

How do I set the type to 'Datetime' for the field 'date' in the table 'outputtable', so that it orders correctly?

Thanks in advance,

H.


Simply use Datetime as column type :D


Cast it to date, like this:

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

or more readably:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜