Skip to content
Advertisement

MySQL – category with product count not showing all results

I am trying to display the count of products along with the category name in the category list.

I was able to achieve this with JOIN, but not all categories are displayed.

I mean the categories with 0 products were not displayed, but I changed the JOIN to LEFT JOIN which displayed only one category with 0 products. There are two more.

This is the query I am trying to execute.

If anyone has any idea, please guide me.

Advertisement

Answer

Your query should fail because the GROUP BY clause is inconsistent with the SELECT columns — c.id is not the same as p.category_id. (Older version of MySQL do accept this syntax.)

You are aggregating by a column that has a NULL value when there is no match. You really want to aggregate by a column in the category table. I would recommend:

Note that the GROUP BY columns match the unaggregated SELECT columns. Also, the as id and as name are redundant, so I removed them.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement