作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我有以下表格:
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/
我只想在 mysql 表中获得获胜者。 SELECT mayor_id, local_unit_id, Value FROM (SELECT mayor_id, local_unit_id,
我是一名优秀的程序员,十分优秀!