在MySQL中,我試圖讓行的量forum_posts
,其中ID等於在forum_posts_threads
,其中thread_id
列等於在forum_threads_forums
,其中forum_id
列匹配的thread_id
列post_id
列一定的價值。爲了說明:MySQL的複雜的多表計數
forum_forums
id name
1 forum1
2 forum2
forum_threads
id title
1 thread1
2 thread2
forum_threads_forums
thread_id forum_id
1 1
1 2
2 2
forum_posts
id title
1 post1
2 post2
forum_posts_threads
post_id thread_id
1 1
2 1
2 2
然後我執行查詢它獲取所有論壇。我想要的是,它計算每個論壇的帖子數量。
因此,就需要回到這樣的事情:
id name post_count
1 forum1 2
2 forum2 3
我已經有以下查詢:
SELECT
forum_forums.id,
forum_forums.name,
forum_forums.description,
COUNT(forum_threads_forums.thread_id) AS thread_count,
forum_categories.id AS category_id,
forum_categories.name AS category_name,
forum_categories.description AS category_description
FROM
forum_forums
LEFT OUTER JOIN
forum_threads_forums
ON
forum_forums.id=forum_threads_forums.forum_id
INNER JOIN
forum_forums_categories
ON
forum_forums.id=forum_forums_categories.forum_id
INNER JOIN
forum_categories
ON
forum_forums_categories.category_id=forum_categories.id
GROUP BY
forum_forums.id
查詢已經能夠計算線程的數量(和做一些其他的東西),但我不確定如何計算帖子,因爲它需要檢查兩個分開的表中的條件。
所以,如果任何人都可以提供一些建議,以便如何調整我的查詢,那將是很棒的。
在此先感謝!
如果用實際的表名替換第一段中的「表1」,「表2」等,你的問題會更清晰。 – Tom 2014-11-01 06:03:51
@Tom我會對任何混淆抱歉 – Qub1 2014-11-01 11:55:44