我目前有以下查询来从表posts
中获取帖子。
$stmt = $db->prepare(
"SELECT p_id,p_title,p_date,p_userid,p_world,p_views,p_thumb,p_link,u_username
FROM posts
INNER JOIN users
ON u_id = p_userid
ORDER BY p_hotness DESC
LIMIT 50");
$stmt->execute();
$stmt->bind_result($p_id,$p_title,$p_date,$p_userid,$p_world,$p_views,$p_thumb,$p_link,$u_username);
while($stmt->fetch()){
$posts[] = [
'p_id' => $p_id,
'p_title' => $p_title,
'p_date' => $p_date,
'p_userid' => $p_userid,
'p_world' => $p_world,
'p_views' => $p_views,
'p_thumb' => $p_thumb,
'p_link' => $p_link,
'u_username' => $u_username
];
};
$stmt->close();
但是我还想从另一个表post_votes
中获取帖子的upvotes和downvotes数量,其中包含以下列:
pv_id | pv_ip | pv_type | pv_postid | pv_userid
pv_type
是0(downvote)或1(upvote)。
SELECT COUNT(*) FROM post_votes WHERE pv_postid = ? AND pv_type = 1 // upvotes
SELECT COUNT(*) FROM post_votes WHERE pv_postid = ? AND pv_type = 0 // downvotes
目前,我可以将此SQL放在显示每个帖子的foreach循环中,但这样做效率很低,因为它在循环的每次迭代中都会进行多次查询。
在上面的第一个查询中,有什么方法可以计算帖子的赞成票数和赞成票数吗?
答案 0 :(得分:3)
尝试此查询
SELECT p_id,p_title,p_date,p_userid,p_world,p_views,p_thumb,p_link,u_username,
sum(IF( pv.pv_type= '1', 1 , 0 )) as upvote, sum(IF( pv.pv_type= '0', 1 , 0 )) as downvote
FROM posts INNER JOIN users ON u_id = p_userid
JOIN post_votes pv ON pv.pv_postid = posts.p_id
ORDER BY p_hotness DESC
LIMIT 50
并尝试此查询,无需投票和投票
SELECT p_id,p_title,p_date,p_userid,p_world,p_views,p_thumb,p_link,u_username,
(select sum(IF( pv.pv_type= '1', 1 , 0 )) from post_votes pv where pv_postid=posts.p_id ) as upvote,(select sum(IF( pv.pv_type= '0', 1 , 0 )) from post_votes pv where pv_postid=posts.p_id ) as downvote
FROM posts INNER JOIN users ON u_id = p_userid ORDER BY p_hotness DESC LIMIT 50