当我有这样的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