MySQL在一个查询中显示类别及其公司计数

时间:2012-02-09 21:43:38

标签: mysql select join left-join categories

我试图在单个查询中显示companyId = 2的类别计数,即使为0:

categories
+--------+-----------+
| catId  |  catName  |
+--------+-----------+
|   1    |   cat1    |
|   2    |   cat2    |
|   3    |   cat3    |

products
+--------+-----------+---------------+---------+
| prodId | prodName  |   companyId   |  catId  |
+--------+-----------+---------------+---------+
|   1    |   prod1   |       2       |    1    |
|   2    |   prod2   |       2       |    3    |
|   3    |   prod3   |       1       |    3    |

SELECT c.catName, COUNT(p.catId) AS prod_catCount
FROM categories c
LEFT JOIN products p ON c.catId=p.catId
WHERE p.companyId=2
GROUP BY c.catId

这导致:

+---------+---------------+
| catName | prod_catCount |
+---------+---------------+
|  cat1   |       1       |
|  cat3   |       1       |

如何让它产生结果:

+---------+---------------+
| catName | prod_catCount |
+---------+---------------+
|  cat1   |       1       |
|  cat2   |       0       | <-- Shows 0 count as well
|  cat3   |       1       |

我认为左联盟会照顾到这一点,但事实并非如此。任何想法如何让这个工作?

1 个答案:

答案 0 :(得分:4)

p.companyId=2WHERE子句移到ON子句

SELECT c.catName, COUNT(p.catId) AS prod_catCount
FROM categories c
LEFT JOIN products p ON c.catId=p.catId AND p.companyId=2
GROUP BY c.catId