向现有查询添加连接和计数会使sums和count函数输出膨胀

时间:2011-12-06 15:46:26

标签: 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.problem_id  
where problem_categories.category_id = 1 GROUP BY problem_title;  

当我在suggested_solutions表和sum(column_in_suggested_solutions_table)上添加另一个连接以查看有问题的建议解决方案的数量时,查询如下所示:

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()函数返回一个膨胀的计数,而suggest_solutions的count函数也返回一个膨胀的数字。

知道我在这里做错了吗?

谢谢!

1 个答案:

答案 0 :(得分:3)

特定suggested_solutions有多个problem_id行,这意味着在原始查询中汇总的行会被夸大。

您可以在派生表中执行group by,然后加入到该表中。

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_categories.category_id = 1也会将LEFT JOINproblem_votes之间的第一个problems转换为INNER JOIN