SQL LEFT JOIN与COUNT(*)问题

时间:2010-08-15 07:42:47

标签: sql mysql count left-join zero

我有以下查询:

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。我该如何解决这个问题?

4 个答案:

答案 0 :(得分:4)

你试过COUNT(products_to_categories.categoryID) AS itemCount吗?我不太确定,但会认为可能问题出在COUNT(*)

答案 1 :(得分:4)

尝试COUNT(product_name)或其他,而不是COUNT(*)

答案 2 :(得分:1)

COUNT(products_to_categories.categoryID)

要求COUNT(*)至少给你1,因为毕竟 1行。具体计数需要特殊处理。

答案 3 :(得分:-1)

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'