sql >> Databasteknik >  >> RDS >> Mysql

Problem vid gruppering

Prova den här (låt mig veta om det fungerar):

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

Här är ett andra alternativ:

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. SQL Server ROWLOCK över en SELECT om den inte existerar INSERT transaktion

  2. PostgreSQL initdb (Databasinitiering) på Linux

  3. Olöst symbol:sql::mysql::get_driver_instance(void)

  4. Hur du formulerar ditt värde som DBA för finanschefer