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