mysql查询组错误结果

时间:2014-04-01 02:30:49

标签: mysql

我正在为网站创建一个简单的论坛应用程序,这是我的表格架构......

这是获取所有类别的mysql查询,total_topics,total_posts和last_topic_date ......

SELECT fc.id, fc.name, fc.var_name, fc.description, fc.dnt, COUNT(ft.id) AS total_topics, COUNT(fp.id) AS total_posts, MAX(ft.dnt) AS last_topic_date 
FROM forum_categories fc
LEFT JOIN forum_topics ft ON ft.category_id = fc.id
LEFT JOIN forum_posts fp ON fp.topic_id = ft.id
GROUP BY fc.id

mysql fiddle

正如您所看到的,我获得了3个total_topic,而该类别中只有2个主题可用。请帮我解决这个问题。感谢。

1 个答案:

答案 0 :(得分:1)

在此处查看已解决的答案:http://sqlfiddle.com/#!2/ad2a6/3

SELECT 
    fc.id, 
    fc.name, 
    fc.var_name, 
    fc.description, 
    fc.dnt, 
    COUNT(DISTINCT ft.id) AS total_topics, 
    COUNT(DISTINCT fp.id) AS total_posts, 
    MAX(ft.dnt) AS last_topic_date -- oldest date for most recent use MIN(ft.dnt) AS last_topic_date 
FROM forum_categories fc
LEFT JOIN forum_topics ft ON ft.category_id = fc.id
LEFT JOIN forum_posts fp ON fp.topic_id = ft.id
GROUP BY fc.id

当您离开加入时,您不会过滤掉空记录,因此您必须在计数中说明DISTINCT以获得正确的COUNT()。 INNER JOINS通常更快,可能是更好的解决方案,除非你不想过滤。