计算三个连接没有给出正确的结果

时间:2013-07-10 09:00:39

标签: mysql count

我有三个表(MySQL)

论坛:此表中的每一行都是论坛中与static_id相关的评论,并通过user_id与作者相关

|match_static_id| date | time | comments | user_id |

匹配:此表包含与其所有信息的匹配

| static_id | localteam_name | visitorteam_name | date | time |.......

iddaa:这个表包含每个匹配的代码(有些匹配在这里没有代码)

|match_static_id| iddaa_code |

我进行如下查询:

SELECT  forum.match_static_id, forum.date, forum.time,
count(forum.comments) 'comments_no', matches.*, users.username, iddaa.iddaa_code
FROM forum
INNER JOIN matches ON forum.match_static_id = matches.static_id
INNER JOIN users on forum.user_id = users.id
LEFT JOIN iddaa on forum.match_static_id = iddaa.match_static_id
GROUP BY forum.match_static_id 
ORDER BY forum.date DESC, forum.time DESC

查询工作正如我所愿(我得到匹配信息,匹配的iddaa代码,如果有的话,以及评论的作者(最后评论))。 问题是在“计数功能”中我应该得到与返回的查询相同的匹配的评论数量(每个值的两倍) 例如,如果我对匹配有5条评论,则返回10 我想知道我的查询的所有部分是否正确,任何帮助都会很好吗?

1 个答案:

答案 0 :(得分:0)

也许它可以包装在子查询中?当我没有表格def +数据时很难。

SELECT Sub.*, COUNT(1) 'comments_no'
FROM
(
SELECT  forum.match_static_id, forum.date, forum.time,
matches.*, users.username, iddaa.iddaa_code
FROM forum
INNER JOIN matches ON forum.match_static_id = matches.static_id
INNER JOIN users on forum.user_id = users.id
GROUP BY forum.match_static_id
) Sub
LEFT JOIN iddaa on Sub.match_static_id = iddaa.match_static_id
ORDER BY forum.date DESC, forum.time DESC