SQL LEFT JOIN 与 COUNT(*) 问题

发布于 2024-09-14 13:14:08 字数 361 浏览 10 评论 0原文

我有以下查询:

SELECT products_categories.categoryID, name, COUNT(*) AS itemCount
FROM products_categories
LEFT JOIN products_to_categories ON products_to_categories.categoryID = products_categories.categoryID
GROUP BY products_categories.categoryID

但仍然存在问题:其中没有产品的类别返回 itemCount = 1 而不是 0。我该如何解决这个问题?

I have the following query:

SELECT products_categories.categoryID, name, COUNT(*) AS itemCount
FROM products_categories
LEFT JOIN products_to_categories ON products_to_categories.categoryID = products_categories.categoryID
GROUP BY products_categories.categoryID

But still there's a problem: categories with no products in them return itemCount = 1 instead of 0. How can I fix this?

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

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

发布评论

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

评论(4

伪装你 2024-09-21 13:14:09

尝试 COUNT(product_name) 或其他任何内容,而不是 COUNT(*)

Try COUNT(product_name) or whatever, instead of COUNT(*).

丿*梦醉红颜 2024-09-21 13:14:09
COUNT(products_to_categories.categoryID)

请求 COUNT(*) 至少会得到 1,因为毕竟有 1 行。具体计数需要具体处理。

COUNT(products_to_categories.categoryID)

Asking for COUNT(*) gives you 1 at least because, after all, there is 1 row. Specific counts need specific treatment.

榆西 2024-09-21 13:14:09
SELECT products_categories.categoryID, name, COUNT(*) AS itemCount
FROM products_categories
LEFT JOIN products_to_categories ON products_to_categories.categoryID = products_categories.categoryID
GROUP BY products_categories.categoryID
WHERE itemCount <> '0'
SELECT products_categories.categoryID, name, COUNT(*) AS itemCount
FROM products_categories
LEFT JOIN products_to_categories ON products_to_categories.categoryID = products_categories.categoryID
GROUP BY products_categories.categoryID
WHERE itemCount <> '0'
安稳善良 2024-09-21 13:14:08

您是否尝试过 COUNT(products_to_categories.categoryID) AS itemCount?我不太确定,但认为问题可能出在 COUNT(*) 上。

Have you tried COUNT(products_to_categories.categoryID) AS itemCount? I am not really sure but would think that maybe the problem lies in the COUNT(*).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文