0

对于一个论坛,我想获取一个forumTopic附加的链接信息,lastPostDate比如lastPostUserNamestarterUserName

问题出现在lastPostUserNameandstarterUserName上。当 aforumTopic只有一个链接的帖子时,它似乎可以正常工作,并且两者lastPostUserName都已starterUserName填充。当有多个帖子链接到一个主题时starterUserNamelastPostUserName只有NULL

数据库的结构是 a formCategoryhas a number of formTopicthe forumTopichas 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
4

1 回答 1

1

试试这个

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' 

子查询 (innerv) 过滤活动记录并按 topicId 对 forumPost 中的记录进行分组。

于 2012-06-06T14:16:35.097 回答