我计算一个项目的投票数量,并且只有两个可能的值:
vote = 1
和vote = 2
。
SELECT COUNT(*) AS count
FROM match_votes
WHERE match_id = :match_id
GROUP BY vote
但是,如果1
没有投票,但2
投票,那么它只会返回1行,因为它不会计算空值。我想返回vote = 1
和vote = 2
的计数,即使该项目没有投票。
另外,我想确保vote = 1
的计数始终是第一行。
答案 0 :(得分:3)
您需要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;