SQL 帮助 - 计算两个表中的行数

发布于 2024-11-16 00:13:51 字数 292 浏览 0 评论 0原文

我有 2 个表:产品和产品。类别

我正在尝试编写 sql 来计算每个类别的产品数量。到目前为止,我有这个:

SELECT `name`, count(*) as `size`
FROM products
INNER JOIN category ON category.`id` = products.`categoryID`
GROUP BY category.`name`

这将返回每个类别名称的列表以及该类别的产品数量。但是,它没有列出包含 0 个产品的类别。我该如何解决这个问题?

I have 2 tables: products & category

I'm trying to write the sql to count the number of products per category. So far I have this:

SELECT `name`, count(*) as `size`
FROM products
INNER JOIN category ON category.`id` = products.`categoryID`
GROUP BY category.`name`

This will return me a list of each category name and the number of products for that category. However it doesn't list categories that have 0 products. How do I solve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

风为裳 2024-11-23 00:13:51

使用右连接。

SELECT `name`, count(*) as `size`
FROM products
RIGHT JOIN category ON category.`id` = products.`categoryID`
GROUP BY category.`name`

Use a right join.

SELECT `name`, count(*) as `size`
FROM products
RIGHT JOIN category ON category.`id` = products.`categoryID`
GROUP BY category.`name`
昵称有卵用 2024-11-23 00:13:51

尝试使用:

SELECT `name`, count(products.id) as `size`
FROM category
LEFT JOIN products ON category.`id` = products.`categoryID`
GROUP BY category.`name`

Try with:

SELECT `name`, count(products.id) as `size`
FROM category
LEFT JOIN products ON category.`id` = products.`categoryID`
GROUP BY category.`name`
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文