我真的很困惑解决这个问题。目前我的项目中有一个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 :(得分:1)
我认为您应该在数据库端执行此操作并重写您的查询:
SELECT ((SELECT COUNT(*) FROM Ratings WHERE TopicID = :current AND Upvote = true) - (SELECT COUNT(*) FROM Ratings WHERE TopicID = :current AND Downvote = true)) AS total_votes
并且在PHP端只需获取total_votes
:
$sample1 = $this->db->prepare("SELECT ((SELECT COUNT(*) FROM Ratings WHERE TopicID = :current AND Upvote = true) - (SELECT COUNT(*) FROM Ratings WHERE TopicID = :current AND Downvote = true)) AS total_votes");
$sample1->bindParam(':current', $id);
$sample1->execute();
$result = $sample1->fetch();
$total_votes = $result->total_votes;