Mysql
 sql >> Base de Dados >  >> RDS >> Mysql

Problema ao agrupar


Tente este (deixe-me saber se funciona):
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
JOIN (SELECT MAX(m.date) as date, top.category_id  
     FROM forum_messages m
     JOIN forum_topics top ON m.topic_id = top.id
     GROUP BY top.category_id) as t
  ON t.category_id = forum_topics.category_id AND t.date = forum_messages.date
WHERE forum_categories.id=6
GROUP BY forum_categories.id

Aqui está uma segunda opção:
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
AND forum_messages.date = (SELECT MAX(date)
                           FROM forum_messages t
                           WHERE t.topic_id = forum_topics.id)
GROUP BY forum_categories.id
ORDER BY forum_categories.date ASC