2012-02-20 185 views
1
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| 
+-----------+----------+--------------------+ 

这是我的情况,我使用线程和注释创建基本论坛。我想按最后评论日期排序,如果没有评论,那么线程的开始日期。我遇到的问题是在我的while循环中试图回显出最后一个回复日期。MySQL GROUP BY - 返回错误日期

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"); 

我的问题不是线程的正确顺序,而是评论日期。在我上面的表格中,如果我试图回显日期,我目前得到的是2012-02-15 22:29:20而不是最近的2012-02-19 19:45:32。

有什么我做错了吗?

我认为这事做与GROUP BY,因为如果我将其更改为GROUP BY chat_comment.date然后在while循环的日期是准确的,但也有重复的,因为我没有被chat_thread.id分组

回答

4

而不是选择最后chat_comment.date,您正在选择一个任意之一。 (有关详细说明,请参阅MySQL Reference Manual, §11.6.3: GROUP BY and HAVING with Hidden Columns)。您需要使用MAX(chat_comment.date)而不仅仅是chat_comment.date

+0

谢谢你,我知道这可能是一些简单的我失踪。我会尽快接受这个答案。 再次感谢! – Jako 2012-02-20 01:26:44

+0

@Jako:不客气! – ruakh 2012-02-20 01:28:47

1

你,如果你想有一个最大值使用MAX(),然后你必须GROUP所有其他列,就像这样:

mysql_query(" 
SELECT chat_thread.id, chat_thread.title, chat_thread.date, 
MAX(chat_comment.date) AS commentDate 
FROM chat_thread 
LEFT JOIN chat_comment ON chat_thread.id = chat_comment.t_id 
GROUP BY chat_thread.id, chat_thread.title, chat_thread.date 
ORDER BY MAX(chat_comment.date) DESC, chat_thread.date DESC");