當我有這樣的MySQL查詢:問題分組
SELECT forum_categories.title, forum_messages.author, forum_messages.date AS last_message
FROM forum_categories
JOIN forum_topics ON forum_topics.category_id=forum_categories.id
JOIN forum_messages ON forum_messages.topic_id=forum_topics.id
WHERE forum_categories.id=6
ORDER BY forum_categories.date ASC
和輸出是如下:
Welcome daniel 2010-07-09 22:14:49
Welcome daniel 2010-06-29 22:14:49
Welcome luke 2010-08-10 20:12:20
Welcome skywalker 2010-08-19 22:12:20
Welcome delicious 2010-10-09 19:12:20
Welcome daniel 2011-11-05 23:12:20
Welcome pierre 2011-11-05 23:12:22
現在,我想使用MAX日化集團的。所以查詢變成:
SELECT forum_categories.title, forum_messages.author, forum_messages.date AS last_message, MAX(forum_messages.date)
FROM forum_categories
JOIN forum_topics ON forum_topics.category_id=forum_categories.id
JOIN forum_messages ON forum_messages.topic_id=forum_topics.id
WHERE forum_categories.id=6
GROUP BY forum_categories.id
ORDER BY forum_categories.date ASC
完美!所需日期是正確的:2011-11-05 23:12:22(該分組的最大日期)。但我也從這種行爲方面得到相應的線用戶(在示例pierre)。
但它需要另一個。
爲什麼?它不選擇整行?我該如何解決這個問題?乾杯
編輯
其實,我應該申請這個分組到這整個查詢:
SELECT forum_categories.title, COUNT(DISTINCT forum_topics.id) AS total_topics, SUM(CASE WHEN forum_messages.original=0 THEN 1 ELSE 0 END) AS total_replies, forum_messages.author, MAX(forum_messages.date) AS last_message
FROM forum_categories
JOIN forum_topics ON forum_topics.category_id=forum_categories.id
JOIN forum_messages ON forum_messages.topic_id=forum_topics.id
GROUP BY forum_categories.id
ORDER BY forum_categories.date
使用MAX(日期)只是從分組記錄中選擇最大日期。您將需要一個子查詢或另一個連接來獲取每個組的最大日期的記錄。所以有很多類似的問題,我會舉一個例子。 – Galz 2011-05-06 23:05:53