1

I have the following table

>> tbl_category

id | category
-------------
0  | A
1  | B
...|...

>>tbl_product

id | category_id | product
---------------------------
0  | 0           | P1 
1  | 1           | P2
...|...          | ...

I can use the following query to count the number of products in a category.

select category, count(tbl.product) from tbl_product 
join tbl_category on tbl_product.category_id = category.id 
group by catregory

However, there are some categories that never have any product belonging to. How do I get these to show up in the query result as well?

1 Answer 1

2

Use a left join:

select c.category, count(tbl.product) 
from tbl_category c left join
     tbl_product p
     on p.category_id = c.id 
group by c.category;

The table where you want to keep all the rows goes first (tbl_category).

Note the use of table aliases to make the query easier to write and to read.

Sign up to request clarification or add additional context in comments.

2 Comments

You might add extra coalesce at count(tbl.product) to show 0 at least coalesce(count(tbl.product),0).
@Lemur . . . Utterly unnecessary. COUNT() returns 0, not NULL if there are no matches.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.