これに似たスレッドがたくさんあることを知っており、多くを調べましたが、解決策を見つけることができませんでした. したがって、カテゴリ (num_type=0)、スレッド (num_type=1)、および投稿 (num_type=2) を格納する「フォーラム」というテーブルが 1 つあります。スレッド/投稿を親のカテゴリ/スレッドに関連付ける列 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 はそうではありません。クエリを 2 つの個別のクエリに分割すると、次のようになります。
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 がどのカテゴリに対応するかを知るために、これらを何らかの方法で組み合わせる必要があります。個別に実行する場合との大きな違いは、2 番目のクエリで、F2.num_Forum によるグループ化を実行できることです。コングロマリット クエリに追加しようとしましたが、問題は解決しませんでした。最初のクエリを修正するために何をする必要があるか知っている人はいますか?