我计算的是一个项目的投票数,只有两个可能的值:

vote = 1vote = 2

SELECT COUNT(*) AS count
FROM match_votes
WHERE match_id = :match_id
GROUP BY vote


但是,如果没有对1的投票,但是对2的投票,则它将仅返回1行,因为它不计算空值。我想返回vote = 1vote = 2的计数,即使该项目没有投票也是如此。

另外,我想确保vote = 1的计数始终是第一行。

最佳答案

您需要一个left join

select v.vote, count(mv.vote)
from (select 1 as vote union all select 2) v left join
     match_votes mv
     on mv.vote = v.vote
group by v.vote;


或者,将结果放在两列中:

select sum(mv.vote = 1) as vote_1, sum(mv.vote = 2) as vote_2
from match_votes mv;

关于mysql - 使用GROUP BY时,COUNT个空值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35957919/

10-12 03:09