5

我有以下表格:

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

值是可以是 1 或 -1 的 tiny_int。

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

$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"));
}

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

4

2 回答 2

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
于 2011-04-20T22:25:55.033 回答
0

我找不到sql_select()您正在使用的函数,但您最好count(*)在 SQL 中使用而不是尝试使用sum(). 您只需要计算它看起来像的行,而不是对这些值求和。你也可以变得更花哨并使用 GROUP BY:

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

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

于 2011-04-20T22:24:41.540 回答