0

这是情况,i 用于表 forum_topics、forum_replies 和 users。_topics 包含所有主题,_replies 包含所有帖子,用户包含所有用户。

我试图将主题列为:

(主题)_ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _(最后回复时间)

(由用户名创建的主题)_ __ _ __ _ __ _ __ _ __ _ __(最后回复)

目前,“主题”和“用户名创建的主题”显示得很好,但是最后一次发布的时间和发布它的用户是错误的。

SQL:

 SELECT 
forum_topics.id,
forum_topics.category,
forum_topics.subject,
forum_topics.created AS topiccreate,
forum_topics.createdby AS topiccreatedby,
forum_replies.topic,
forum_replies.created AS repliecreated,
forum_replies.createdby AS repliecreatedby,
usertopic.firstname AS topicfirstname,
usertopic.lastname AS topiclastname,
userreplie.firstname AS repliefirstname,
userreplie.lastname AS replielastname,
usertopic.id as topicid, 
userreplie.id

FROM forum_topics

JOIN forum_replies ON forum_replies.topic = forum_topics.id
JOIN users usertopic ON forum_topics.createdby = usertopic.id
JOIN users userreplie ON forum_replies.createdby = userreplie.id

WHERE forum_topics.category =  '1'
GROUP BY forum_replies.topic
ORDER BY forum_replies.created DESC 

如何让“最后回复时间”和“最后回复时间”显示正确?我尝试删除 Group By,然后它检索所有帖子,但是我只想要每个主题的最新帖子数据。

至于现在使用 GROUP BY 时,它只检索一次所有主题(正确),但最后一次回复的时间和最后一次回复的时间显示不正确,因为它似乎检索了每个主题的第一篇文章的数据。

希望你能理解我的问题!:/

4

2 回答 2

0

您还需要一个条件才能获得最新的回复。以下是您在join子句中的操作方式:

FROM forum_topics
JOIN forum_replies ON forum_replies.topic = forum_topics.id
JOIN users usertopic ON forum_topics.createdby = usertopic.id
JOIN users userreplie ON forum_replies.createdby = userreplie.id
JOIN (select topic, max(created) as maxcreated
      from forum_replies
      group by topic
     ) frmax on frmax.topic = forum_replies.topic and
                frmax.maxcreated = forum_replies.created;

我认为你不需group by要这样做之后。

于 2013-07-06T12:52:40.807 回答
0

尝试在 SQL 查询中删除 group by 和 order by 并检查。

于 2013-07-06T12:57:01.920 回答