[英]Postgres SQL: getting group count
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?
如何将它们也显示在查询结果中?
Use a left join
: 使用
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
). 您要保留所有行的表排在第一位(
tbl_category
)。
Note the use of table aliases to make the query easier to write and to read. 请注意,使用表别名可以使查询更易于编写和阅读。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.