目前我的项目中有一个jQuery upvote插件。因此,每次我点击upvote它都会将db中的值保存为true,每次投票都将它保存在数据库中,并将值保存为false,并将另一列中的值保存为0.我所要做的就是计算总票数就像堆栈溢出一样。即使是现在,我对如何解决这个问题感到困惑。我最终在php中制作了这段代码,这也使我的整个程序变得缓慢:
$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--;
}
}
对于上面的例子,我的计数器应该是0
答案 0 :(得分:1)
我认为通过更多的研究,您显示的决定向上或向下计数的条件可以简化得相当多。但是,这是一个实现条件的SQL语句:
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
如果只有“真实”值计数,这可能会起到作用:
SELECT
SUM(IF(Upvote='true',1,0)) - SUM(IF(Downvote='true',1,0)) as `votes`
FROM Ratings
WHERE TopicD = :current