0

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 の最初のスレッドのカウントのみが返されます。

サブクエリでテーブル エイリアスを指定しようとすると、複数の行が返されたというエラーが返されます。

クエリの内容に関する不一致はなぜですか? また、メイン クエリで計算フィールドとして使用されたときに最初のスレッドのみがカウントされるのはなぜですか?

4

1 に答える 1

0

t.forum_id と f.id の両方がサブクエリの外部でのみ関連するため、サブクエリはこれと同等です。

IF(t.forum_id = f.id, 
(SELECT COUNT(p.id) 
FROM post p
WHERE p.thread_id = t.id
GROUP BY 1)
, 0) AS total_posts

おそらく次のようなものが必要です。

SELECT f.name AS forum_name, COUNT(p.id) AS total_posts
FROM forum AS f
JOIN thread AS t ON t.forum_id = f.id
JOIN post AS p ON p.thread_id = t.id
GROUP BY f.id

そのクエリは、フォーラムごとに 1 行を返し、投稿数を正しく含める必要があります。

フォーラムに投稿がない場合、そのフォーラムはこのクエリによって返されないことに注意してください。注意が必要な場合は、JOIN の代わりに LEFT JOIN を使用して変更できます。

于 2011-01-25T16:54:40.820 に答える