从链接表中获取论坛主题信息中的用户名

时间:2012-06-06 13:47:11

标签: mysql sql

对于论坛,我想要提取forumTopic,其中包含lastPostDatelastPostUserNamestarterUserName等附加链接信息。

问题出现在lastPostUserNamestarterUserName上。当forumTopic只有一个链接的帖子时,它似乎正常工作,并且lastPostUserNamestarterUserName都已填充。如果有多个帖子链接到某个主题,则只会填充starterUserNamelastPostUserNameNULL

数据库的结构是formCategoryformTopicforumTopic的数量为forumPost,而forumPostuser相关联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

{{1}}

1 个答案:

答案 0 :(得分: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中的记录进行记录和分组。