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
但是,有一些类别从来没有任何产品属于。我怎样才能让这些显示在查询结果中呢?
您可以在计数(tbl.product)处添加额外的合并,以至少显示'coalesce(count(tbl.product),0)'。 – Lemjur
@Lemur。 。 。完全没有必要。 COUNT()返回0,如果没有匹配则返回NULL。 –