开发者

Trouble with MySQL joining tables and using COUNT function

开发者 https://www.devze.com 2023-03-04 12:39 出处:网络
I\'m trying to build a forum that consists of three tables. A forum table, a topic table, and a posts table.

I'm trying to build a forum that consists of three tables. A forum table, a topic table, and a posts table.

On the page displaying all the forums I would like it to show the number of topics for each forum, and the number of posts in that forum. Pretty standard stuff. I'm having some trouble wit开发者_开发百科h the MySQL query however. This is what I'm using:

SELECT f.* , COUNT(t.topic_id) AS topics, COUNT(p.post_id) AS posts
FROM forums AS f
LEFT JOIN forums_topics AS t ON f.forum = t.forum_id
LEFT JOIN forums_posts AS p ON t.topic_id = p.topic_id
GROUP BY f.forum

This will return one row for each forum, however the topic count and posts counts return equal to each other. The post count is correct, so the problem is in the topic count.

The tables are structured with forums_posts contains the id number of the topic it belongs to, it does not contain the id number of the forum it belongs to. The forums_topics table contains the id number of the forum it belongs to.

How can my query be corrected? Would it be better if I added the forum_id a post belongs to in the forums_posts table?

Thank you for your advice.


Problem is that COUNT(t.topic_id) will count the topic ids. You'd want to count the distinct number of topic IDs.

Something like

SELECT f.* , COUNT( DISTINCT (t.topic_id) ) ...
0

精彩评论

暂无评论...
验证码 换一张
取 消