Javier Enríquez
Javier Enríquez

Reputation: 630

MySQL select only rows with max datetime grouped by foreign

I'm implementing a forum system and I have these tables:

I'm trying to get all the forums but I want to add also the last created forum_reply.

I'm really stuck in this. Any help please

For example:

I have 3 forums:

and this topics (id, title, forum_id):

finally, this replies (id, content, forum_topic_id, created_at)

So my final result should look like this:

(forums.id, forum.title, forum_topics.id, forum_topics.title, forum_replies.id, forum_replies.content, forum_replies.timestamp)

EDIT

SQLFiddle full with tables and data

Upvotes: 0

Views: 47

Answers (1)

pala_
pala_

Reputation: 9010

There are two steps to this process - the first is identifying the most recent post. The second is to retrieve the rest of the information (such as the topic title and reply content) which requires joining to that result set again.

select *
from forums f 
  left join forum_topics ft
    on f.id = ft.forum_id
  left join forum_replies fp
    on ft.id = fp.forum_topic_id
  left join (
    SELECT f.id, MAX(fp.created_at) created_at
      FROM forums f 
        INNER JOIN forum_topics ft
          ON f.id = ft.forum_id
        INNER JOIN forum_replies fp
          ON ft.id = fp.forum_topic_id
      GROUP BY f.id
  ) q
    on fp.created_at = q.created_at
      and f.id = q.id
    where fp.created_at = q.created_at
      or fp.id is null;

Upvotes: 1

Related Questions