如何显示不存在的值的行

时间:2019-03-31 11:51:03

标签: mysql

我有一个查询

 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 个答案:

答案 0 :(得分:0)

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`