Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 将联接和计数添加到现有查询会扩大总和和计数函数的输出_Mysql_Sql - Fatal编程技术网

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
之间的第一个
左连接
转换为
内部连接