views:

80

answers:

5

I have the following query:

SELECT products_categories.categoryID, name, COUNT(*) AS itemCount
FROM products_categories
LEFT JOIN products_to_categories ON products_to_categories.categoryID = products_categories.categoryID
GROUP BY products_categories.categoryID

But still there's a problem: categories with no products in them return itemCount = 1 instead of 0. How can I fix this?

+1  A: 
COUNT(products_to_categories.categoryID)

Asking for COUNT(*) gives you 1 at least because, after all, there is 1 row. Specific counts need specific treatment.

Tomalak
+2  A: 

Have you tried COUNT(products_to_categories.categoryID) AS itemCount? I am not really sure but would think that maybe the problem lies in the COUNT(*).

Florian Grell
A: 
SELECT products_categories.categoryID, name, COUNT(*) AS itemCount
FROM products_categories
LEFT JOIN products_to_categories ON products_to_categories.categoryID = products_categories.categoryID
GROUP BY products_categories.categoryID
WHERE itemCount <> '0'
fergNab
A: 

Perhaps a subquery is what you want...

SELECT categoryID,
       name,
       (SELECT COUNT(*)
            FROM products_to_categories
            WHERE products_to_categories.categoryID = products_categories.categoryID) AS itemCount
    FROM products_categories
    GROUP BY categoryID;
Brian Hooper
+2  A: 

Try COUNT(product_name) or whatever, instead of COUNT(*).

Hamid Nazari