简体   繁体   中英

How to Sum Columns From Two Result Sets in MySQL

I have the following table:

ratings:

ID | post_id | rating_type

The rating_type field is either 'thumb-up' or 'thumb-down'. I want to get a result set telling me what the highest rated posts are. The following query gives me a result set with the number of up votes for each unique post_id.

SELECT COUNT(post_id) as number_up, post_id FROM wp_sp_post_ratings WHERE rating_type = 'thumb-up' GROUP BY post_id

That is great! I can do similarly for the thumb-down rating type. However, what I need is to get the total rating where each thumb-up gives a post one point and each thumb down gives a post a negative point. Then, I need to order that by the total amount of rating. So, say we have the following:

post 1 has 3 up votes and 2 down votes post 2 has 14 up votes and 33 down votes post 3 has 4 up votes and 0 down votes

I'd like to see a result set like the following:

post_id | total_rating
3 | 4
1 | 1
2 | -19

I have no idea how to do this. I've been banging my head against the documentation and Google for about 2 hours now, so I was hoping that SO could be my savior.

SELECT SUM(CASE WHEN rating_type = 'up' THEN 1 WHEN rating_type = 'down' THEN -1 END CASE)
FROM posts
GROUP BY post_id

PS It's better to keep up and down votes as numbers (+1 and -1) rather than strings.

Initially, why not store a thumbs up as 1 and a thumbs down as -1 directly? Quassnoi was quicker with the case statement....

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