Mysql 将联接和计数添加到现有查询会扩大总和和计数函数的输出
我有一个正常工作的查询:Mysql 将联接和计数添加到现有查询会扩大总和和计数函数的输出,mysql,sql,Mysql,Sql,我有一个正常工作的查询: select problems.problem_id , problem_title , sum( vote ) as totalVotes from problems left join problem_votes on problems.problem_id = problem_votes.problem_id left join problem_categories on problems.problem_id = problem_categories.
select problems.problem_id , problem_title , sum( vote ) as totalVotes
from problems
left join problem_votes on
problems.problem_id = problem_votes.problem_id
left join problem_categories on
problems.problem_id = problem_categories.problem_id
where problem_categories.category_id = 1 GROUP BY problem_title;
当我在summed\u solutions
表和sum(建议的\u solutions\u表中的列)上添加另一个连接以查看有多少建议的解决方案存在问题时,查询如下所示:
select problems.problem_id , problem_title , sum( vote ) as totalVotes , count(solution_name) from problems
left join problem_votes on
problems.problem_id = problem_votes.problem_id
left join problem_categories on
problems.problem_id = problem_categories.problem_id
left join suggested_solutions on
problems.problem_id = suggested_solutions.problem_id
where problem_categories.category_id = 1 GROUP BY problem_title;
第二个查询的问题是,虽然它仍然返回相同数量的行,但原始的sum()函数返回的计数数量是膨胀的,而建议的\u解决方案的count函数也返回膨胀的数字
知道我做错了什么吗
谢谢 对于特定的
问题id
有多个建议的\u解决方案
行,这意味着原始查询中求和的行会膨胀
您可以在派生表中执行groupby
,然后加入到该表中
SELECT problems.problem_id,
problem_title,
SUM(vote) AS totalVotes,
Solution_Count
FROM problems
LEFT JOIN problem_votes
ON problems.problem_id = problem_votes.problem_id
LEFT JOIN problem_categories
ON problems.problem_id = problem_categories.problem_id
LEFT JOIN (SELECT COUNT(solution_name) AS Solution_Count,
problem_id
FROM suggested_solutions
GROUP BY problem_id) ss
ON problems.problem_id = ss.problem_id
WHERE problem_categories.category_id = 1
GROUP BY problem_title;
请注意,您的WHERE problem\u categories.category\u id=1
将problem\u投票
和problems
之间的第一个左连接
转换为内部连接