mysql - 当字段的计数为零时,如何通过聚合查询从组返回的值为零(0)?

标签 mysql

如果 Table.id 的计数为零,我想从类型查询中返回一个值(在本例中为零)。

 SELECT COUNT(Table1.id) AS AccountID, Table2.typeName AS Types
 FROM Table1
 LEFT JOIN Table3
 ON Table1.productID = Table3.productID
 LEFT JOIN Table2
 ON Table3.categoryID = Table2.CategoryID
 WHERE Table3.account_id = 51
 GROUP BY Table2.typeName;

This is the result that I would like to get

This is the result that I am currently getting

Table1
id      ProductID
1       1
1       1
2       2
2       1
1       1
id in this table 1 references categoryID in table2
---------------------------------------------------------

Table2
categoryID      typeName
1               SUV
2               BMW
3               Toyota
4               Audi
5               Suzuki
---------------------------------------------------------


Table3
categoryID      ProductID       account_id
2               1               51
1               2               52
3               1               51
categoryID is table3 references categoryID in table2
----------------------------------------------------------


My expected result should look like this

Count   Types
0       Toyota
0       Audi
0       Suzuki
3       SUV
2       BMW

我想计算表 1 中所有 ID 及其相应类型名称的数量。如果 id 不存在,我希望返回带有相应 typeName 的 0。

最佳答案

以下查询将起作用:

SELECT 
 COUNT(Table1.id) AS AccountID, 
 Table2.typeName  AS Types
 FROM Table2
 LEFT JOIN Table3
 ON Table3.categoryID = Table2.CategoryID
 AND Table3.account_id = 51
 LEFT JOIN Table1
 ON Table1.id = Table3.CategoryID     
 GROUP BY Table2.typeName;

Click here for DEMO

关于mysql - 当字段的计数为零时,如何通过聚合查询从组返回的值为零(0)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47023954/

相关文章:

php - 使用 laravel eloquent 将左连接中的 null 值替换为 N/A

mysql - 在mysql中按字母数字排序

mysql - Offset是否应该在Sql查询的末尾指定?

mysql - 根据 SQL 中的组过滤掉重复项

mysql - 如何在 mysql 中获取当前期间或最近的周年纪念日(月份或年份)?

php - 尝试上传图像时出现 undefined index 错误

mysql - Node JS mySQL 三重查询和信息丢失

java - Spring Boot 异常 "java.lang.IllegalArgumentException: Not a managed type:"

mysql - 如何在一个查询中链接 SQL 选择结果?

MySQL 客户端/服务器 : TCP response packet with ACK flag but without PSH