table: chat_thread
+-----------+----------+--------------------+
| id | title | date |
+-----------+----------+--------------------+
| 1 | Thread 1 | 2012-02-16 01:12:40|
| 2 | Thread 2 | 2012-02-17 02:32:44|
+-----------+----------+--------------------+
table: chat_comment
+-----------+----------+--------------------+
| id | t_id | date |
+-----------+----------+--------------------+
| 1 | 1 | 2012-02-19 19:45:32|
| 2 | 1 | 2012-02-15 22:29:20|
+-----------+----------+--------------------+
Here’s my situation, I creating a basic forum with threads and comments. I want to order by the last comment date, and if there is no comments, then the thread start date. The problem I’m having is trying to echo out the last reply date in my while loop.
mysql_query("
SELECT *,
chat_comment.date AS commentDate,
chat_thread.date AS threadDate
FROM chat_thread
LEFT JOIN chat_comment ON chat_thread.id = chat_comment.t_id
GROUP BY chat_thread.id
ORDER BY commentDate DESC, threadDate DESC");
My issue isn’t the correct order of the threads, but the comment dates. In my tables above, if I’m trying to echo out the date, I’m currently getting 2012-02-15 22:29:20 instead of the more recent 2012-02-19 19:45:32.
Is there something I’m doing wrong?
I think it has something to do with the GROUP BY, because if I change it to GROUP BY chat_comment.date then the dates in the while loop are accurate, but there are duplicates, because I am not grouping by the chat_thread.id
Instead of selecting the last
chat_comment.date, you are selecting an arbitrary one. (See MySQL Reference Manual, §11.6.3:GROUP BYandHAVINGwith Hidden Columns for a detailed explanation of this.) You need to useMAX(chat_comment.date)instead of justchat_comment.date.