sql >> Databáze >  >> RDS >> Mysql

Problém při seskupování

Zkuste toto (dejte mi vědět, jestli to funguje):

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

Zde je druhá možnost:

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. Jak používat implementaci AES_DECRYPT() MySQL pomocí Pythonu

  2. SQL Server 2005 – Exportujte tabulku programově (spusťte soubor .sql a znovu ji vytvořte)

  3. Oracle – Upravte existující tabulku tak, aby se sloupec automaticky zvýšil

  4. Připojte se, chcete-li zobrazit konkrétní data v laravel v nástroji pro tvorbu dotazů