Mark
Mark

Reputation: 776

php date and time sorting chronologically

I tried the following query to get the latest comment on top.

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;

But am getting the 'comment_date' like:

12:58AM on 08-16-2012

12:05AM on 08-21-2012

11:54PM on 08-20-2012

01:38AM on 08-16-2012

Here comment_date is DATETIME.

Currently am sorting date and time separately like,

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

Is there any better solution ?

Thanks

Upvotes: 2

Views: 339

Answers (1)

John Woo
John Woo

Reputation: 263713

Your query is correct. But you need to sort it to the original column (comment_date) because its data type is datetime. What you had done was your ordered it by the name of your alias with is now string. Try this,

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;

Upvotes: 2

Related Questions