论坛MySQL类别,主题,帖子

时间:2012-05-28 03:39:25

标签: mysql multithreading forum categories posts

我知道有很多类似于此的线程,我看了很多,但无法找到解决方案。所以,我有一个名为“论坛”的表,其中包含我的类别(num_type = 0),主题(num_type = 1)和帖子(num_type = 2)。有一个列num_parent将Thread / Post与父类别/线程相关联。对于我遇到问题的查询,我试图获取所有类别,每个类别中的总线程数以及每个类别的线程内的总帖子数。要做到这一点,我正在努力:

select F.*
, count(F2.num_Forum) as num_ThreadCount
, count(F3.num_Forum) as num_PostCount
, max(F3.dte_Created) as dte_LastPost
from forum F
left outer join forum F2
on F.num_Forum=F2.num_Parent and F2.num_Type=1
left outer join forum F3
on F2.num_Forum=F3.num_Parent and F3.num_Type=2
where F.num_Type=0 and F.num_Inactive=0
group by F.num_Forum
order by F.num_Sticky desc, F.dte_Created desc

dte_LastPost和num_PostCount正确输出。 num_ThreadCount不是。如果我将查询分解为两个单独的查询:

select F.* 
, count(F2.num_Forum) as num_ThreadCount
from forum F
left outer join forum F2
on F.num_Forum=F2.num_Parent and F2.num_Type=1
where F.num_Type=0 and F.num_Inactive=0
group by F.num_Forum
order by F.num_Sticky desc, F.dte_Created desc

select count(F3.num_Forum) as num_PostCount
from forum F2
left outer join forum F3
on F2.num_Forum=F3.num_Parent and F3.num_Type=2
where F2.num_Type=1 and F2.num_Inactive=0
group by F2.num_Forum
order by F2.num_Sticky desc, F2.dte_Created desc

我得到了正确的计数。但是,我需要以某种方式组合这些,以便我知道num_PostCount对应于哪个类别。我在单独做的时候看到的最大区别是,在第二个查询中,我可以通过F2.num_Forum进行分组。我尝试将其添加到集团查询中,但它没有解决我的问题。任何人都知道我需要做些什么来修复我的第一个查询?

1 个答案:

答案 0 :(得分:0)

好的,我能够弄清楚查询以链接三个表而不在Posts表中放置一个列以将其直接链接到Category。相反,Categories链接到Threads,它链接到Posts,向下和向上链接。

select C.*
, count(TP.num_Thread) as num_ThreadCount
, coalesce(sum(TP.num_PostCount), 0) as num_PostCount
from forum_categories C 
left join 
(select count(P.num_Post) as num_PostCount, 
T.num_Thread, T.num_CParent, T.num_Inactive
from forum_threads T
left outer join forum_posts P
on P.num_TParent=T.num_Thread and P.num_Inactive=0
where T.num_Inactive=0
group by T.num_Thread) TP 
on C.num_Category=TP.num_CParent and TP.num_Inactive=0
where C.num_Inactive=0
group by C.num_Category
order by C.num_Sticky desc, C.dte_Created desc