我有一个查询

 SELECT COUNT(*) as total, sales_dept FROM receipts
 WHERE receipts.sales_dept IN ('co', 'cl', 'wi')
 GROUP BY receipts.sales_dept`


产生结果:

total sales_dept
1     co
5     cl


但是我想要的结果是:

total sales_dept
1     co
5     cl
0     wi


我尝试使用值离开联接,但结果仍然相同

SELECT COUNT(*) as total, sales_dept FROM receipts
LEFT JOIN (
   SELECT 'co' AS val
   UNION ALL
   SELECT 'cl'
   UNION ALL
   SELECT 'wi'
) s on `receipts`.`sales_dept` = `s`.`val`
WHERE `receipts`.`sales_dept` IN ('co', 'cl', 'wi')
GROUP BY `receipts`.`sales_dept`

最佳答案

1)在第二个查询中只需将left更改为right,因为您希望查询的所有值都放在join单词的“右侧”。

2)删除where。它已通过连接过滤。

SELECT COUNT(*) as total, sales_dept FROM receipts
RIGHT JOIN (
   SELECT 'co' AS val
   UNION ALL
   SELECT 'cl'
   UNION ALL
   SELECT 'wi'
) s on `receipts`.`sales_dept` = `s`.`val`
GROUP BY `receipts`.`sales_dept`

关于mysql - 如何显示不存在的值的行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55440615/

10-09 19:26