MySQL只选择最大日期时间按外部分组的行

时间:2015-06-11 00:50:04

标签: mysql

我正在实施一个论坛系统,我有这些表格:

  • forums id titlecreated_at
  • forum_topicsidtitle forum_id created_at
  • forum_repliesidcontent forum_topic_id created_at

我试图获取所有论坛但我想添加最后创建的forum_reply。

我真的陷入了困境。请帮忙

例如:

我有3个论坛:

  • 1,forum1
  • 2,forum2
  • 3,forum3

和这个主题(id,title,forum_id):

  • 1,topic1_forum1,1
  • 2,topic1_forum2,2
  • 3,topic2_forum2,2
  • 4,topic1_forum3,3
  • 5,topic2_forum3,3

最后,这个回复(id,content,forum_topic_id,created_at)

  • 1,content,1,2015-01-01 00:00:00
  • 2,content,1,2015-02-01 20:00:00
  • 3,content,2,2015-02-01 22:00:00
  • 4,content,2,2015-02-01 22:30:00
  • 5,content,3,2015-01-01 00:00:00
  • 6,content,4,2015-01-01 00:00:00
  • 7,content,5,2015-01-02 20:00:00
  • 8,content,5,2015-01-03 00:00:00

所以我的最终结果应该是这样的:

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

  • 1,forum1,1,topic1_forum1,2,content,2015-02-01 20:00:00
  • 2,forum2,2,topic1_forum2,4,content,2015-02-01 22:30:00
  • 3,forum3,5,topic2_forum3,8,content,2015-01-03 00:00:00

修改

SQLFiddle full with tables and data

1 个答案:

答案 0 :(得分:1)

此过程分为两个步骤 - 第一步是确定最近的帖子。第二个是检索需要再次加入该结果集的其余信息(例如主题标题和回复内容)。

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;