For a forum i want to fetch a forumTopic with additional, linked information like the lastPostDate, lastPostUserName and starterUserName.
The problem arises with the lastPostUserName and starterUserName. When a forumTopic has only one linked post it seems to work correctly and both the lastPostUserName as the starterUserName are filled. When there are multiple posts linked to a topic only the starterUserName is filled and the lastPostUserName is NULL
The structure of the database is a formCategory has a number of formTopic the forumTopic has a number of forumPost and a forumPost is linked to 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
Try this
The subquery (innerv) filter active records and groups the records in the forumPost by topicId.