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的行?谢谢。
你必须使用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')
将被计算在内。
由于您使用的是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;
使用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;