2014-10-31 57 views
0

在MySQL中,我試圖讓行的量forum_posts,其中ID等於在forum_posts_threads,其中thread_id列等於在forum_threads_forums,其中forum_id列匹配的thread_idpost_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 

查詢已經能夠計算線程的數量(和做一些其他的東西),但我不確定如何計算帖子,因爲它需要檢查兩個分開的表中的條件。

所以,如果任何人都可以提供一些建議,以便如何調整我的查詢,那將是很棒的。

在此先感謝!

+0

如果用實際的表名替換第一段中的「表1」,「表2」等,你的問題會更清晰。 – Tom 2014-11-01 06:03:51

+0

@Tom我會對任何混淆抱歉 – Qub1 2014-11-01 11:55:44

回答

1

認爲您正在嘗試計算forum_threads_forums中包含線程的帖子數量。有幾種方法可以做到這一點。

最簡單的方法可能只是加入forum_posts_threads表並在post_id上執行COUNT DISTINCT。由於笛卡爾的緣故,你還必須更改你的thread_count來執行COUNT DISTINCT

SELECT 
    forum_forums.id, 
    forum_forums.name, 
    forum_forums.description, 
    COUNT(DISTINCT forum_threads_forums.thread_id) AS thread_count, 
    COUNT(DISTINCT forum_posts_threads.post_id) AS post_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 
LEFT OUTER JOIN 
    forum_posts_threads 
ON 
    forum_threads_forums.thread_id=forum_posts_threads.thread_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 

如果有一些需要應用到forum_posts表的標準,你反而會在你的SELECT子句添加子查詢。像這樣的東西(加入你的WHERE條款)。它將引用您的主FROM子句中的forum_threads_forums.thread_id。

(SELECT COUNT(DISTINCT forum_posts.post_id) post_count 
FROM forum_posts 
     JOIN forum_post_threads ON forum_posts.post_id = forum_post_threads.post_id 
WHERE forum_post_threads.thread_id = forum_threads_forums.thread_id 
     [ADD IN YOUR ADDITIONAL WHERE CONDITIONS] 
) as post_count