如果行不存在,如何按计数分组?

时间:2017-07-19 09:42:42

标签: mysql

例如,表格category_description包含以下行

name    | category_id | nav_id
History | 62          |  1
Romance | 61          |  1
mysql   | 59          |  1
mssql   | 60          |  1

然后product_to_category有以下行

product_id | category_id
 55        |   62
 54        |   62

我正在尝试使用以下查询来计算product_to_category表中的产品数量

select name,count(a.category_id) from category_description a, 
product_to_category b 
where a.category_id = b.category_id group by name;

我得到以下结果

+---------+----------------------+
| name    | count(a.category_id) |
+---------+----------------------+
| History |                    2 |
+---------+----------------------+

但我正在尝试计算空数据,例如我有以下输出

+---------+----------------------+
| name    | count(a.category_id) |
+---------+----------------------+
| History |                     2|
|  mysql  |                     0|
|  mssql  |                     0|
|Romance  |                     0|
+---------+----------------------+

我不知道从哪里需要改变。

1 个答案:

答案 0 :(得分:2)

select name,count(b.category_id) 
from category_description a
LEFT JOIN product_to_category b  ON a.category_id = b.category_id
group by name;

尝试以上查询。

您不需要添加条件,而不是我已将条件添加到 ON CLAUSE 而不是 INNER JOIN 您可以尝试使用 LEFT JOIN