2017-07-10 27 views
1

我有如下表Postgres的SQL:让组计数

>> tbl_category 

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

>>tbl_product 

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

我可以使用下面的查询来计算一个类别的产品数量。

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

但是,有一些类别从来没有任何产品属于。我怎样才能让这些显示在查询结果中呢?

回答

2

使用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; 

要保留所有的行表先行(tbl_category)。

请注意使用表别名来使查询更容易编写和读取。

+0

您可以在计数(tbl.product)处添加额外的合并,以至少显示'coalesce(count(tbl.product),0)'。 – Lemjur

+1

@Lemur。 。 。完全没有必要。 COUNT()返回0,如果没有匹配则返回NULL。 –