【问题标题】:php date and time sorting chronologicallyphp日期和时间按时间顺序排序
【发布时间】:2012-08-16 10:42:12
【问题描述】:

我尝试了以下查询以获取顶部的最新评论。

SELECT u.id, comments, DATE_FORMAT(comment_date, '%h:%i%p on %m-%d-%Y') AS comment_date_time FROM mytable m INNER JOIN users u ON m.added_by = u.id

UNION

SELECT c.id comments, DATE_FORMAT(comment_date, '%h:%i%p on %m-%d-%Y') AS comment_date_time FROM mytable m INNER JOIN contacts c ON m.added_by = c.id
ORDER BY comment_date_time desc;

但我得到的“comment_date”如下:

2012 年 8 月 16 日上午 12:58

2012 年 8 月 21 日上午 12:05

2012 年 8 月 20 日晚上 11:54

2012 年 8 月 16 日上午 01:38

这里的comment_date 是DATETIME。

目前正在分别对日期和时间进行排序,

DATE_FORMAT(comment_date, '%h:%i%p') AS comment_time
DATE_FORMAT(comment_date, '%m-%d-%Y') AS comment_date

有没有更好的解决方案?

谢谢

【问题讨论】:

    标签: php mysql date sorting time


    【解决方案1】:

    您的查询是正确的。但是您需要将其排序到原始列(comment_date),因为它的数据类型是datetime。你所做的是用你的alias 的名字订购它,现在是string。试试这个,

    SELECT id, comments, comment_date_time
    FROM
    (
    SELECT u.id, comments, 
           DATE_FORMAT(comment_date, '%h:%i%p on %m-%d-%Y') AS comment_date_time,
           comment_date
    FROM mytable m INNER JOIN users u ON m.added_by = u.id
    UNION
    SELECT c.id comments, 
           DATE_FORMAT(comment_date, '%h:%i%p on %m-%d-%Y') AS comment_date_time,
           comment_date
    FROM mytable m INNER JOIN contacts c ON m.added_by = c.id
    ) x
    ORDER BY x.comment_date desc;
    

    【讨论】:

    • @zerkms ORDER BY comment_date desc;
    • 我也试过了,但是在“订单子句”中得到“未知列 'comment_date'”
    • @VTP:你需要在SELECT中额外选择原始comment_date
    • @VTP 我刚刚更新了查询。如果它现在显示您想要的结果,您可以运行吗?
    • @John Woo:感谢您的快速回复。我得到了输出:)
    猜你喜欢
    • 2013-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-09
    相关资源
    最近更新 更多