I am trying to execute a MySQL query to find the latest active threads (and the most recent comment for each thread) in a web forum. The topics are stored in two tables, forum_topics and forum_responses , where each forum_topic has many forum_responses .
Here I do a search on forum_reponses attached to forum_topics , with downward sorting on forum_response.id :
select t.id, t.title, r.id, r.body from forum_responses r inner join forum_topics t on (r.forum_topic_id = t.id) order by r.id desc; +----+--------------+----+----------------------------------+ | id | title | id | body | +----+--------------+----+----------------------------------+ | 17 | New Topic | 69 | yes | | 19 | Test Topic 1 | 68 | This is a test | | 17 | New Topic | 64 | hey yo | | 19 | Test Topic 1 | 63 | Test Topic Starter | | 18 | Test Topic | 62 | Test. | | 18 | Test Topic | 61 | Test | | 17 | New Topic | 60 | Another test response. | | 17 | New Topic | 59 | Test response. | | 17 | New Topic | 54 | What should this topic be about? | +----+--------------+----+----------------------------------+
Ok, so far so good. But it returns duplicates - I just want to have the most recent answers to forum topics. Therefore, I am adding GROUP BY to my query so that we can group by topic id:
select t.id, t.title, r.id, r.body from forum_responses r inner join forum_topics t on (r.forum_topic_id = t.id) group by t.id order by r.id desc; +
But now we have a problem: it is grouped by the identifier of the forum topic, but it is not interesting, we do not receive the topics of our forum sorted by the latest actions, and the forum responses associated with them are not the latest.
What's going on here? Is there a way to modify this query to get a list of the most recent forum topics, as well as their latest comments?
source share