【发布时间】: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 我会的,很抱歉有任何混淆
标签: php mysql pdo aggregate-functions