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

问题描述 投票:0回答:3
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;

预期产量: -

ID交易中获得

3     0

4     0

6     3

7     9

8     4

9     0

目前的输出: -

ID交易中获得

6     3

7     9

8     4

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

mysql sql
3个回答
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
投票

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

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

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;

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;
© www.soinside.com 2019 - 2024. All rights reserved.