我正在实施一个论坛系统,我有这些表格:
forums
: id
,title
,created_at
forum_topics
:id
,title
, forum_id
created_at
forum_replies
:id
,content
, forum_topic_id
created_at
我试图获取所有论坛但我想添加最后创建的forum_reply。
我真的陷入了困境。请帮忙
例如:
我有3个论坛:
和这个主题(id,title,forum_id):
最后,这个回复(id,content,forum_topic_id,created_at)
所以我的最终结果应该是这样的:
(forums.id,forum.title,forum_topics.id,forum_topics.title,forum_replies.id,forum_replies.content,forum_replies.timestamp)
答案 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;