SQL LEFT JOIN 与 COUNT(*) 问题
我有以下查询:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试
COUNT(product_name)
或其他任何内容,而不是COUNT(*)
。Try
COUNT(product_name)
or whatever, instead ofCOUNT(*)
.请求
COUNT(*)
至少会得到 1,因为毕竟有 1 行。具体计数需要具体处理。Asking for
COUNT(*)
gives you 1 at least because, after all, there is 1 row. Specific counts need specific treatment.您是否尝试过
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 theCOUNT(*)
.