我想计算和排序一个主要类别的频率(请参阅表结构的SQLFiddle)。但我想显示“0”值,因此如果产品未分配categoryId,则此categoryId的频率应为“0”。
我当前的SQL看起来像这样。
SELECT
category.categoryId,
category.name,
COUNT(*) AS frequency
FROM
Categories category
LEFT JOIN
Product entry ON entry.categoryId = category.categoryId
WHERE
category.parentId = 1
GROUP BY category.categoryId
ORDER BY COUNT(*) DESC
结果
| categoryId | name | frequency |
|------------|------------------|-----------|
| 2 | Sub Category 1-2 | 3 |
| 4 | Sub Category 1-4 | 1 |
| 3 | Sub Category 1-3 | 1 |
如果我制作一个RIGHT JOIN
未分配的类别,则根本不会显示(但我在结果中需要它)。
我需要的结果应该是这样的:
| categoryId | name | frequency |
|------------|------------------|-----------|
| 2 | Sub Category 1-2 | 3 |
| 4 | Sub Category 1-4 | 1 |
| 3 | Sub Category 1-3 | 0 |
有没有办法像上面的结果一样显示“0”频率?
答案 0 :(得分:1)
您需要count(entity.categoryId)
SELECT
c.categoryId,
c.name,
COUNT(e.categoryId) AS frequency
FROM
Categories c
LEFT JOIN
Product e ON e.categoryId = c.categoryId
WHERE
c.parentId = 1
GROUP BY c.categoryId
ORDER BY frequency DESC
答案 1 :(得分:1)
我认为这是您需要的查询:
SELECT
category.categoryId,
category.name,
COUNT(category.parentId) AS frequency
FROM
Categories category
LEFT JOIN
Product entry ON entry.categoryId = category.categoryId
WHERE
category.parentId = 1 or category.parentId is null
GROUP BY category.categoryId
ORDER BY COUNT(*) DESC