I have 3 tables: problems, categories, and a joining table for problem_categories
I am trying to get and count all the categories associated with a problem, and count how many problems are associated with each problem.
Here is my query which doesn’t return correct results:
SELECT
category_name ,
categories.category_id ,
problems.problem_id,
COUNT(problems.problem_id) as num_problems
FROM
problem_categories
left JOIN
categories
on
problem_categories.category_id = categories.category_id
left join
problems
on
problem_categories.problem_id = problems.problem_id
WHERE
problem_categories.problem_id = 266
GROUP BY
problems.problem_id , category_name
but as soon as I take out the where clause, it returns all the categories and correct counts of problems. But the trick is that I need to query this for a particular problem_id
Any way to adjust this query to get it right? What am I doing incorrectly here?
Thanks!!
Your question is somewhat unclear. How can you count problems if you are selecting a specific one? If you want to count categories associated with a particular problem you do this (I am assuming you have foreign keys and no duplicates in the problem_categories table):
then join to problem table if you need to print out more problem information (for efficiency, always get the detail last). If you are wanting to count problem -> category -> problem then do:
Again if you want to show the problem details, join to the problem table to get them. If you want the num_problems and num_categories together join the first query to the second one before joining to the problem table to get the problem detail. i.e.: