我有一个论坛,用户可以发布问题,并可以进行投票和投票。
我希望得到每个帖子的upvote
和downvote
。
我之前做的是在3组查询中做到这一点。
$data = mysqli_query($con,"select * from posts");
while($row = mysqli_fetch_assoc($data)){
$pid = $row['post_id'];
$up = mysqli_fetch_assoc(mysqli_query("SELECT COUNT(*) as c FROM up WHERE post_id = $pid"))['c'];
$down = mysqli_fetch_assoc(mysqli_query("SELECT COUNT(*) as c FROM down WHERE post_id = $pid"))['c'];
}
任何人都可以告诉我如何在单个查询中执行这些操作,因为如果在第一个查询中获得了大量posts
,则会有很多查询要执行。< / p>
答案 0 :(得分:1)
您可以使用子查询并将所有内容放在第一个查询中。
这可能是一个好的开始:
$data = mysqli_query($con, "select posts.*, " .
"(SELECT COUNT(*) FROM up WHERE post_id = posts.post_id) as totalUp, " .
"(SELECT COUNT(*) FROM down WHERE post_id = posts.post_id) as totalDown " .
"from posts");
while($row = mysqli_fetch_assoc($data)){
// ...
}
答案 1 :(得分:0)
你可以使用相关子查询来获得upvotes 和downvotes根据帖子ID计算
SELECT p.*,
( select count(*) from up where post_id = p.post_id ) as upVotesCount,
( select count(*) from down where post_id = p.post_id ) as downVotesCount,
FROM posts p