sql >> Database teknologi >  >> RDS >> Mysql

Problem ved gruppering

Prøv denne (giv mig besked, hvis den virker):

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

Her er en anden mulighed:

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


  1. Hvad er hurtigere, VÆLG DISTINCT eller GROUP BY i MySQL?

  2. Langsom migration til skyen

  3. PostgreSQL:opdatering med venstre ydre selv-tilslutning ignoreret

  4. WebApp (Tomcat-jdbc) Pooled DB-forbindelse, der kaster opgivelse af undtagelse