select 每个 post php mysql 的反对票和赞成票
select down and up votes for each post php mysql
我有一个论坛,用户可以在其中 post 提问,也可以投赞成票和反对票。
我想获取每个 post 的 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
那么就会有很多要做的查询。
你可以为此使用相关子查询 where upvotes
并且根据 post 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
您可以使用子查询并将所有内容放在第一个查询中。
这可能是一个好的开始:
$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)){
// ...
}
我有一个论坛,用户可以在其中 post 提问,也可以投赞成票和反对票。
我想获取每个 post 的 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
那么就会有很多要做的查询。
你可以为此使用相关子查询 where upvotes 并且根据 post 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
您可以使用子查询并将所有内容放在第一个查询中。
这可能是一个好的开始:
$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)){
// ...
}