gpt4 book ai didi

php - 统计正反票数 :

转载 作者:可可西里 更新时间:2023-11-01 07:05:40 25 4
gpt4 key购买 nike

我有以下表格:

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

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

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

最佳答案

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

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

关于php - 统计正反票数 :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5737251/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com