Currently I have a jQuery upvote Plugin in my project. So, with every I click upvote it saves the value in the db as a true, with every vote taken back it save the value as false in the database and saves the value in the other column as 0. All I was trying to do is to count the total number of votes just like stack overflow does. Even now I am so confuse to on how to solve this issue. I end up making this code in php which is also make my whole program slow:
$sample1 = $this->db->prepare("SELECT * from Ratings WHERE TopicID = :current");
$sample1->bindParam(':current', $id);
$sample1->execute();
$RES1 = $sample1->fetchAll(PDO::FETCH_ASSOC);
$upVote = 0;
foreach ($RES1 as $mk){
if(($mk['Upvote'] === 'true') && ($mk['Downvote'] ==='false')){
$upVote++;
}
else if(( $mk['Upvote'] ==='false') && ($mk['Downvote'] === 'true')){
$upVote--;
}
else if(($mk['Upvote'] === 'false') && ($mk['Downvote'] === 'false')){
$upVote--;
}
else if(($mk['Downvote'] === 'false')){
$upVote++;
}
else if(($mk['Downvote'] === 'true') && ($mk['Upvote'] ==='0') || ($mk['Upvote'] === 'false')){
$upVote--;
}
}
For the above example my counter should be be 0
I think with a little more study, the conditions you show to decide up or down count could be simplified quite a bit. But, here's a SQL statement that implements your conditions:
SELECT
SUM(
IF(Upvote='true' AND Downvote='false',1,
IF(upvote='false' AND Downvote='true',-1,
IF(Upvote='false' AND Downvote='false',-1,
IF(Downvote='false',1,
IF(Downvote='true' AND (Upvote='0' OR Upvote=false),-1,0)
)
)
)
)) as `votes`
FROM Ratings
WHERE TopicD = :current
If only 'true' values count, this might do the trick:
SELECT
SUM(IF(Upvote='true',1,0)) - SUM(IF(Downvote='true',1,0)) as `votes`
FROM Ratings
WHERE TopicD = :current