I have this working query which works correctly:
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;
when I add another join on a suggested_solutions table and a sum(column_in_suggested_solutions_table) to see how many suggested solutions there are for a problem, the query looks like this:
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;
The problem with the second query is that while it still returns the same number of rows, the original sum() function returns an inflated number of counts, and the count function for suggested_solutions also returns an inflated number.
Any idea what I am doing wrong here?
Thanks!
There are multiple
suggested_solutionsrows for a particularproblem_idwhich means that the rows getting summed in your original query get inflated.You can do the
group byin a derived table and join onto that instead.Note that also your
WHERE problem_categories.category_id = 1converts the firstLEFT JOINbetweenproblem_votesandproblemsto anINNER JOIN