简体   繁体   English

比较和计数mysql行中的值

[英]Compare and count values in mysql rows

upVote   DownVote
|true   | 0
|true   | 0
|0      | true
|true   | 0
|true   | 0
|0      | true

I have columns like this above in my sql table. 我的sql表中有上述类似的列。 I want to count the total number of upVotes - Downvotes just like stackOverflow. 我想计算upVotes-Downvotes的总数,就像stackOverflow一样。 But for some reason I am having hard time with sql syntax. 但是由于某种原因,我在使用SQL语法时遇到了困难。

SELECT COALESCE(sum(CASE WHEN upvote THEN 1 ELSE 0 END),0) from Ratings WHERE TopicID = :topicsID

I have seen the above sql query example somewhere but not sure I am heading in the right direction.Help is appreciated 我在某个地方看到了上面的sql查询示例,但不确定我是否朝着正确的方向前进。

I guess you need to subtract on sum(upvote) and sum(DownVote) 我想你需要减去sum(upvote)sum(DownVote)

SELECT sum(upvote) - sum(DownVote)
from Ratings 
WHERE TopicID = :topicsID

Fiddle: http://sqlfiddle.com/#!9/b1644c/8 小提琴: http ://sqlfiddle.com/#!9/b1644c/8

I think One vote column with a boolean value is enough. 我认为一个布尔值的vote列就足够了。

Because True can mean upvote ,False can mean DownVote 因为真正可能意味着upvote ,假可能意味着DownVote

CREATE TABLE Ratings
(
    Vote BOOL
);
INSERT INTO Ratings VALUES 
(TRUE),
(TRUE),
(0),
(0),
(TRUE),
(TRUE),
(0);

SELECT sum(CASE WHEN Vote THEN 1 ELSE 0 END) - 
   sum(CASE WHEN Vote THEN 0 ELSE 1 END) as vote
from Ratings 
WHERE TopicID = :topicsID

Fiddle: http://sqlfiddle.com/#!9/727c2b/3 小提琴: http ://sqlfiddle.com/#!9/727c2b/3

select COUNT(*) from ratings WHERE upvote=true AND TopicID = :topicsID ?

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

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