2013-02-21 47 views
1

我有2个表格论坛主题表和论坛评论。MYSQL COUNT HAVING问题

我想通过计算每个主题中有多少评论来获取所有论坛主题的列表。

评论表包含每个主题的论坛主题的PK。

我已经试过

SELECT 
    `forum_topics`.`topic_id`, 
    `forum_topics`.`topic_name`, 
    `forum_topics`.`topic_info`, 
    `forum_topics`.`topic_img`, 
    `forum_topics`.`creation_date`, 
    `forum_topics`.`is_deleted` 
FROM 
    `forum_topics` 
JOIN 
    `forum_comments` 
ON 
    `forum_comments`.`topic_id` = `forum_topics`.`topic_id` 
GROUP BY 
    `forum_topics`.`topic_id` 
HAVING 
    COUNT(`forum_comments`.`comment_id`) >= 0 
    AND `forum_topics`.`review_status` = 'reviewed'; 

这似乎不返回任何结果,但也没有任何错误

希望有人能帮助

+0

数据库结构的示例? – 2013-02-21 13:11:25

+0

我在您的查询中看不到任何错误。你确定你在'forum_comments'有正确的'topic_id'有一些记录吗? – Aioros 2013-02-21 13:12:55

+0

你确定这个状态是正确的吗? – 2013-02-21 13:13:29

回答

3

试试这个

SELECT forum_topics.topic_id, forum_topics.topic_name, forum_topics.topic_info, 
    forum_topics.topic_img, forum_topics.creation_date, forum_topics.is_deleted 
FROM forum_topics 
JOIN forum_comments ON forum_comments.topic_id = forum_topics.topic_id 
WHERE forum_topics.review_status = 'reviewed' 
GROUP BY forum_topics.topic_id 
HAVING COUNT(forum_comments.comment_id) >= 0 
+0

谢谢,它似乎左加入固定它。我给你打了个勾,因为我更了解你的查询。标记的答案也是正确的 – 2013-02-21 13:38:31

+0

欢迎您!,很好,它可以帮助你! – 2013-02-21 15:08:22

3

请尝试以下:

SELECT 
    `forum_topics`.`topic_id`, 
    `forum_topics`.`topic_name`, 
    `forum_topics`.`topic_info`, 
    `forum_topics`.`topic_img`, 
    `forum_topics`.`creation_date`, 
    `forum_topics`.`is_deleted`, 
    `forum_topics`.`review_status`, 
    COUNT(`forum_comments`.`comment_id`) count_comments 
FROM 
    `forum_topics` 
LEFT JOIN 
    `forum_comments` 
ON 
    `forum_comments`.`topic_id` = `forum_topics`.`topic_id` 
order by case when `forum_topics`.`review_status` = 'reviewed' then 1 else 2 end, 
     count_comments desc