2010-08-15 88 views
4

我有以下查詢: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。我怎樣才能解決這個問題?

+0

而不是LEFT JOIN只是使用JOIN – YoK 2010-08-15 07:49:41

+0

@YoK感謝您的建議。你能解釋爲什麼JOIN在這種情況下會更好嗎? – naburi 2010-08-15 07:54:54

回答

4

你試過COUNT(products_to_categories.categoryID) AS itemCount?我不太確定,但會認爲問題可能在於COUNT(*)

1
COUNT(products_to_categories.categoryID) 

問計COUNT(*)給你1至少因爲,畢竟還有 1排。具體計數需要特定的治療。

-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' 
4

嘗試COUNT(product_name)或什麼的,而不是COUNT(*)