We’re currently stuck trying to make a simple (?) SQL query.
We have these two tables:
create table `post` (
`id` integer primary key
)
create table `vote` (
`id` integer primary key,
`post_id` references `post`.`id`, // Well ok, it's a foreign key then...
`value` int // 1 for a positive vote, or zero for a negative one
)
We’re trying to build a select that would, for each post, return the number of positive and negative votes: SELECT post.id, <positive count>, <negative count> ...
While this is not hard to do with sub-selects, the challenge begins when we try to do this without sub-selects, but with join. We’re using left outer join, and the problems arise when a post has only positive or negative votes.
While I understand the problem, I can’t figure out how to do that only with join, yet I’m confident it can be done without sub-selects. How would you do that ?
(Well, I did not include my current query, so that it won’t guide you to the wrong direction…)
Previous answer was rubbish, I forgot to
GROUP. Here’s an alternative that usesCASE, I THINK it handles theNULLcase (since theWHENclause will beNULL) but you may need to useCOALESCEafter all…:Previous (incorrect) answer: