MySQL复杂的多表计数
Posted
技术标签:
【中文标题】MySQL复杂的多表计数【英文标题】:MySQL complex multi table count 【发布时间】:2014-12-28 05:38:06 【问题描述】:在mysql中,我试图获取forum_posts
中的行数,其中id等于forum_posts_threads
中的post_id
列,其中thread_id
列等于forum_threads_forums
中的thread_id
列,其中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
该查询已经能够计算线程的数量(并执行一些其他操作),但我不确定如何计算帖子,因为它需要检查两个单独表中的条件。
因此,如果有人可以就如何调整我的查询提供一些建议,那就太好了。
提前致谢!
【问题讨论】:
如果将第一段中的“table 1”、“table 2”等替换为实际的表名,您的问题会清晰很多。 @Tom 我会的,很抱歉有任何混淆 【参考方案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
【讨论】:
以上是关于MySQL复杂的多表计数的主要内容,如果未能解决你的问题,请参考以下文章