计算正面和负面投票的数量:

时间:2011-04-20 22:11:43

标签: php mysql voting

我有以下表格:

post (id, title, content) etc
author (id, username) etc
author_vote (post_id, author_id, value)

值是一个tiny_int,可以是1或-1。

我想计算每个帖子的正面和负面投票数量:

$posts = sql_select($link, "SELECT post.*, author.username 
                            FROM post, author 
                            AND author.id = post.author_id");

为什么以下代码不起作用?

array_walk($posts, function(&$post, $link){
   $post['positive'] = sql_select($link, "SELECT SUM(value) FROM author_vote WHERE post_id = $post['id']
                                            AND value  = 1");

   $post['negative'] = abs(sql_select($link, "SELECT SUM(value) FROM author_vote WHERE post_id = $post['id']
                                            AND value  = -1"));
});

我也尝试过以下操作,这会导致每个帖子的所有投票都相同:

foreach ($posts as &$post)
{
   $id = $post['id'];
   $post['positive'] = (int)sql_select($link, "SELECT SUM(value) FROM author_vote WHERE post_id = $id
                                           AND value  = 1");
   $post['negative'] = (int)abs(sql_select($link, "SELECT SUM(value) FROM author_vote WHERE post_id = $id
                                               AND value  = -1"));
}

还有什么方法可以做到这一点,而不必为每个帖子多次查询数据库?如何(像这样)不断变化的东西(缓存)是什么?

2 个答案:

答案 0 :(得分:5)

您可以在一个查询中进行计数:

Select Sum( Case When value < 0 Then 1 Else 0 End ) As NegVotes
    , Sum( Case When value > 0 Then 1 Else 0 End ) As PosVotes
From author_vote
Where post_id = ...

如果你想要每个帖子的正面和负面投票:

Select post_id
    , Sum( Case When value < 0 Then 1 Else 0 End ) As NegVotes
    , Sum( Case When value > 0 Then 1 Else 0 End ) As PosVotes
From author_vote
Group By post_id

如果您想要合并第一个查询和第二个查询,可以获得:

Select post....
    , author.username 
    , Coalesce(post_count.NegVotes,0) As NegVotes
    , Coalesce(post_count.PosVotes,0) As PosVotes
From post
    Join author
        On author.id = post.author_id
    Left Join   (
                Select post_id
                    , Sum( Case When value < 0 Then 1 Else 0 End ) As NegVotes
                    , Sum( Case When value > 0 Then 1 Else 0 End ) As PosVotes
                From author_vote
                Group By post_id
                ) As post_count
        On post_count.post_id = post.post_id

答案 1 :(得分:0)

我找不到您正在使用的函数sql_select(),但您可能最好在SQL中使用count(*)而不是尝试sum()。您只需计算它看起来的行,而不是对值求和。你也可以得到一点点发烧友并使用GROUP BY:

SELECT value, count(value) AS value_count FROM author_vote WHERE post_id = $id GROUP BY value

这将为每个唯一值返回一行。返回的每一行都将使用该值报告唯一值和行数。