MySQL复杂多表计数

时间:2014-10-31 19:56:44

标签: php mysql pdo aggregate-functions

在MySQL中,我尝试获取forum_posts中的行数,其中id等于post_idforum_posts_threads列的thread_id列,thread_id列等于forum_threads_forums中的forum_id列,其中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}}

查询已经能够计算线程数量(并做其他一些事情),但我不确定如何计算帖子,因为它需要检查两个单独表格中的条件。

因此,如果有人可以提供一些关于如何调整我的查询的建议那么好。

提前致谢!

1 个答案:

答案 0 :(得分: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
相关问题