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
Your query is correct. But you need to sort it to the original column (
comment_date) because its data type isdatetime. What you had done was your ordered it by the name of youraliaswith is nowstring. Try this,