【问题标题】:SQL LEFT JOIN with COUNT(*) problemSQL LEFT JOIN with COUNT(*) 问题
【发布时间】:2010-08-15 07:42:46
【问题描述】:

我有以下疑问:

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

【问题讨论】:

  • 只使用 JOIN 而不是 LEFT JOIN
  • @YoK 感谢您的建议。你能解释一下为什么在这种情况下 JOIN 会更好吗?

标签: sql mysql count left-join zero


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:
      COUNT(products_to_categories.categoryID)
      

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

      【讨论】:

        【解决方案4】:
        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'
        

        【讨论】:

          猜你喜欢
          • 2021-12-21
          • 1970-01-01
          • 1970-01-01
          • 2019-04-23
          • 1970-01-01
          • 2016-04-28
          • 2021-06-27
          • 2013-03-01
          • 2017-02-08
          相关资源
          最近更新 更多