选择所有带有所有帖子的评论php mysql [英] select all comments with all posts php mysql
问题描述
我有一个论坛,用户可以在其中发布问题,发表评论和发布推文.
I have a forum where users can post questions and can comment and tweet.
我想获取每个帖子的所有comments
和tweets
.
I want to get all the comments
and tweets
of each post.
我以前所做的是在3组查询中进行的.
What i did previously was do that in 3 sets queries.
$data = mysqli_query($con,"select * from posts");
while($row = mysqli_fetch_assoc($data)){
$pid = $row['post_id'];
$dataCo = mysqli_query("SELECT comments.* FROM comments WHERE post_id = $pid");
$dataTw = mysqli_query("SELECT tweets.* FROM tweets WHERE post_id = $pid");
//2 while loop for comments and tweets
}
任何人都可以告诉我如何在一个查询中执行这些操作,因为如果在第一个查询中有很多posts
,那么将有很多查询要做.
Can anyone show me how can i do these things in one single query because if a get a lot of posts
in 1st query then there will be lots of queries to do.
OR
也许有更快的方法吗?
推荐答案
也许您可以使用Mysql IN子句
Maybe you can use Mysql IN clause
http://www.tutorialspoint.com/mysql/mysql-in- Clause.htm
在您的示例中,您总是有2 * n + 1个对DB的查询.在此查询中,返回的行数为n
In your example you have always 2*n + 1 queries to DB. Where n in number of returned rows in this query
$data = mysqli_query($con,"select * from posts");
如果使用mysql IN子句,则只有3个查询.
If you use mysql IN Clause you will have only 3 queries.
您的查询应类似于
$dataCo = mysqli_query("SELECT comments.* FROM comments WHERE post_id IN (1,2,3,4)");
$dataTw = mysqli_query("SELECT tweets.* FROM tweets WHERE post_id IN (1,2,3,4)");
数字"1,2,3,4"是您第一个问题中返回的post_id.
Numbers "1,2,3,4" are post_id returned in your first question.
这篇关于选择所有带有所有帖子的评论php mysql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!