0

I'm counting the number of votes given to an item, and there's only two possible values:

vote = 1 and vote = 2.

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

However if there has been no votes for 1 but votes for 2 then it will only return 1 row since it doesn't count null values. I want to return count for vote = 1 and vote = 2, even if there's no votes for the item.

Also, I want to ensure that the count for vote = 1 is always the first row.

1 Answer 1

3

You need a 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;

Or, put the results in two columns:

select sum(mv.vote = 1) as vote_1, sum(mv.vote = 2) as vote_2
from match_votes mv;
Sign up to request clarification or add additional context in comments.

1 Comment

first query still didn't count the nulls I think, but the second one worked

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.