PHP フォーラムを開発しています。このフォーラムは、フォーラム、スレッド、投稿、ユーザーの 4 つのデータベース テーブルを使用します。
私のランディング ページには、すべてのフォーラムのリストに加えて、最新のスレッド (結合と内部結合によって達成される)、合計スレッド (単純なカウント サブクエリ)、および合計投稿の列があります。
上記のすべてを返す適切なサイズのクエリがあり、投稿の合計を除いて、すべてがうまく機能しています。
したがって、主なクエリは次のとおりです。
select f.id as forum_id,
f.name as forum_name,
f.description,
t.forum_id,
#this subquery counts total threads in each forum
(select count(t.forum_id)
from thread t
where t.forum_id = f.id
) as total_threads,
#this query counts total posts for each forum
(SELECT COUNT( p.id )
FROM post p
WHERE p.thread_id = t.id
AND t.forum_id = f.id
GROUP BY f.id) as total_posts,
t.id as thread_id,
t.name as thread_name,
t.forum_id as parent_forum,
t.user_id,
t.date_created,
u.id as user_id,
u.username
from forum f
# this join finds all latest threads of each forum
join
(select forum_id, max(date_created) as latest
from thread
group by forum_id) as d on d.forum_id = f.id
#and this inner join grabs the rest of the thread table for each latest thread
inner join thread as t
on d.forum_id = t.forum_id
and d.latest = t.date_created
join user as u on t.user_id = u.id
したがって、上記の総投稿サブクエリに注意を向けると、スレッド ID = 各スレッドの ID、次に = 各フォーラムの ID であるすべての投稿をカウントしていることに気付くでしょう。このクエリを単独で使用すると (メインクエリの他の場所で使用されているテーブルエイリアスを含めます)完全に機能します。
ただし、メイン クエリのコンテキストで使用され、テーブル エイリアスが別の場所で提供されている場合は、p/forum の最初のスレッドのカウントのみが返されます。
サブクエリでテーブル エイリアスを指定しようとすると、複数の行が返されたというエラーが返されます。
クエリの内容に関する不一致はなぜですか? また、メイン クエリで計算フィールドとして使用されたときに最初のスレッドのみがカウントされるのはなぜですか?