简体   繁体   English

如何在MySQL中从两个结果集中求和

[英]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'. rating_type字段为“竖起大拇指”或“竖起大拇指”。 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. 以下查询为我提供了一个结果集,其中包含每个唯一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 帖子1具有3赞成和2反对票帖子2具有14赞成和33反对票帖子3具有4赞成和0反对票

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. 大约2个小时以来,我一直在与文档和Google交流,我希望SO可以成为我的救星。

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. PS最好以数字(+1和-1)而不是字符串来保持上下投票。

Initially, why not store a thumbs up as 1 and a thumbs down as -1 directly? 最初,为什么不直接将大拇指存储为1并将大拇指存储为-1? Quassnoi was quicker with the case statement.... Quassnoi的案件陈述速度更快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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