对于论坛,我想要提取forumTopic
,其中包含lastPostDate
,lastPostUserName
和starterUserName
等附加链接信息。
问题出现在lastPostUserName
和starterUserName
上。当forumTopic
只有一个链接的帖子时,它似乎正常工作,并且lastPostUserName
和starterUserName
都已填充。如果有多个帖子链接到某个主题,则只会填充starterUserName
且lastPostUserName
为NULL
数据库的结构是formCategory
有formTopic
个forumTopic
的数量为forumPost
,而forumPost
与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
。
{{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中的记录进行记录和分组。