对于一个论坛,我想获取一个forumTopic
附加的链接信息,lastPostDate
比如lastPostUserName
和starterUserName
。
问题出现在lastPostUserName
andstarterUserName
上。当 aforumTopic
只有一个链接的帖子时,它似乎可以正常工作,并且两者lastPostUserName
都已starterUserName
填充。当有多个帖子链接到一个主题时starterUserName
,lastPostUserName
只有NULL
数据库的结构是 a formCategory
has a number of formTopic
the forumTopic
has a number offorumPost
和 aforumPost
链接到 a user
。
SELECT forumTopic.*,
COUNT( forumPost.id ) AS postCount,
MAX(forumPost.date) AS lastPostDate,
(SELECT name FROM user AS u1 WHERE u1.id = forumPost.posterUserId AND forumPost.date = MAX(forumPost.date) )
AS lastPostUserName,
(SELECT name FROM user AS u2 WHERE u2.id = forumPost.posterUserId AND forumPost.date = MIN(forumPost.date) )
AS starterUserName
FROM forumCategory
LEFT JOIN forumTopic ON forumCategory.id = forumTopic.forumCategoryId
LEFT JOIN forumPost ON forumPost.forumTopicId = forumTopic.id
WHERE forumCategory.rewrittenName='someforumcategory'
AND forumCategory.active='Y'
AND forumTopic.active='Y'
AND forumPost.active='Y'
GROUP BY forumTopic.id
ORDER BY forumPost.date ASC