0

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

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 进行分组。我尝试将它添加到集团查询中,但它并没有解决我的问题。有人知道我需要做什么来修复我的第一个查询吗?

4

1 回答 1

0

好的,我能够找出链接三个表的查询,而无需在 Posts 表中放置一列以将其直接链接到类别。相反,Categories 链接到 Threads,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
于 2012-05-30T00:57:49.667 回答