私はPHPフォーラムを開発しています。 このフォーラムはフォーラム、スレッド、投稿、ユーザーの4つのデータベーステーブルを使用します。異なる結果を返す孫のテーブルのMySQLの数
私のランディングページには、すべてのフォーラムの一覧と最新のスレッドの列(結合と内部結合によって実現)、合計の3つのサブクエリ、合計の投稿があります。
私は上記のすべてを返すかなりのサイズのクエリを持っており、すべての投稿は非常にうまく動作しています。
メイン・クエリは、このようです:
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
だから、あなたは 上記総投稿サブクエリにあなたの注意を指示する場合、私はすべての記事を数えていますhtatあなたが気づくところ、そのスレッドID =のID各スレッドの各スレッドは、各フォーラムのIDです。このクエリだけを使用すると(メインクエリの別の場所で使用されているテーブルエイリアスも含めて)、完全に動作します。
しかし、メインクエリのコンテキストで使用され、別名でテーブルエイリアスが提供されている場合、最初のスレッドp /フォーラムのカウントのみが返されます。
サブクエリにテーブルエイリアスを指定しようとすると、複数の行が返されたというエラーが返されます。
なぜクエリの内容が矛盾し、なぜメインクエリの計算フィールドとして使用された場合に最初のスレッドのみがカウントされるのですか?