Reputation: 4723
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
Upvotes: 0
Views: 32
Reputation: 3139
Try this
SELECT forumTopic.*,
innerv.*,
(SELECT name FROM user AS u1 WHERE u1.id = innerv.first_user)
AS startedUserName,
(SELECT name FROM user AS u2 WHERE u2.id = innerv.last_user )
AS lastUserName
FROM forumTopic
LEFT JOIN forumCategory ON forumCategory.id = forumTopic.forumCategoryId
LEFT JOIN (
SELECT forumTopicId, MAX(date) AS LAST_POSTED_dATE, MIN(date) as FIRST_POSTED_DATE,
SUBSTRING_INDEX(
GROUP_CONCAT(posterUserId ORDER BY date),
',',
1
) as first_user,
SUBSTRING_INDEX(
GROUP_CONCAT(posterUserId ORDER BY date),
',',
-1
) as last_user, count(1) as posts_under_topic
FROM forumPost where forumPost.active='Y'
GROUP BY forumTopicId ) innerv ON innerv.forumTopicId = forumTopic.id
WHERE forumCategory.rewrittenName='someforumcategory'
AND forumCategory.active='Y'
AND forumTopic.active='Y'
The subquery (innerv) filter active records and groups the records in the forumPost by topicId.
Upvotes: 1