修改 SQL 查询以包含没有值的案例

Modify SQL query to include cases without a value

我有这个数据库任务,我需要在其中编写一个查询“以显示每个类别的 ID 和名称,以及属于该类别的产品数量”。我能够解决它并使用这个查询。

SELECT Category.Id, Category.Name, COUNT(Category.Name) 
FROM Category, Product 
WHERE (CategoryId = Category.Id) 
GROUP BY Category.Id;

但我想修改它以显示所有类别,即使是那些没有产品的类别。卡在这部分。感谢任何帮助。

你可以left join:

select c.id, c.name, count(p.categoryid) cnt_products
from category c
left join product p on p.categoryid = c.id
group by c.id;

相关子查询也是一个很好的解决方案,它避免了外部聚合:

select c.*,
    (select count(*) from product p where p.categoryid = c.id) cnt_products
from category c