即使计数值为0 mysql也要选择行

时间:2018-03-05 07:26:02

标签: mysql sql

select c.id, count(*) as 'Transactions' from voucher v 
right join consumer c on v.consumer_id = c.id
where v.voucher_state in ('REDEEMED', 'EXPIRED') and c.country = 'INDIA'
group by c.id;

预期输出: -

标识事务

3 0

4 0

6 3

7 9

8 4

9 0

当前输出: -

标识事务

6 3

7 9

8 4

如何选择count = 0的行?感谢。

3 个答案:

答案 0 :(得分:2)

您必须使用LEFT JOIN,在左侧放置consumer表并移动

 v.voucher_state in ('REDEEMED', 'EXPIRED'):

ON子句:

select c.id, count(v.consumer_id) as 'Transactions' 
from consumer c
left join voucher v  on v.consumer_id = c.id on v.voucher_state in ('REDEEMED', 'EXPIRED')
where c.country = 'INDIA'
group by c.id;

上述查询将返回满足条件的所有 customer.id

customer.country = 'INDIA'

只有在voucher表中具有

的匹配记录的客户
voucher.voucher_state in ('REDEEMED', 'EXPIRED')

将被计算在内。

答案 1 :(得分:1)

由于您使用的是RIGHT JOIN,因此左表中的过滤条件必须位于ON子句中。原因是,过滤将在优化器将其与正确的表连接之前发生。 WHERE子句将在最终结果中进行过滤。

另外,你必须只计算左表中的行(例如COUNT(v.consumer_id)))而不是COUNT(*),否则,每个c.id总会有一个计数。< / p>

select c.id, count(v.consumer_id) as 'Transactions' 
from voucher v 
     right join consumer c 
       on v.consumer_id = c.id 
          and v.voucher_state in ('REDEEMED', 'EXPIRED')
where  c.country = 'INDIA'
group  by c.id;

答案 2 :(得分:0)

使用IFNULL

select c.id,IFNULL(COUNT(*), 0) as 'Transactions' from voucher v 
right join consumer c on v.consumer_id = c.id
where v.voucher_state in ('REDEEMED', 'EXPIRED') and c.country = 'INDIA'
group by c.id;