简体   繁体   中英

Count the number of votes per post

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 uses CASE , I THINK it handles the NULL case (since the WHEN clause will be NULL ) but you may need to use COALESCE after all...:

SELECT post.id, SUM(CASE WHEN a.vote > 0 THEN 1 ELSE 0 END) up, SUM(CASE WHEN a.vote < 0 THEN 1 ELSE 0 END) down FROM post LEFT JOIN vote a ON (a.post_id = post.id) GROUP BY post.id

Previous (incorrect) answer:

It sounds like you need to use COALESCE to force a NULL to zero - the following might work but is untested:

 SELECT post.id, SUM(COALESCE(a.vote,0)), SUM(COALESCE(b.vote,0)) FROM post LEFT JOIN vote a ON (a.post_id = post.id AND value > 0) LEFT JOIN vote b ON (b.post_id = post.id AND value < 0) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM