简体   繁体   中英

select all comments with all posts php mysql

I have a forum where users can post questions and can comment and tweet.

I want to get all the comments and tweets of each post.

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

}

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

Maybe there is a faster way to do ?

Maybe you can use Mysql IN clause

http://www.tutorialspoint.com/mysql/mysql-in-clause.htm

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");

If you use mysql IN Clause you will have only 3 queries.

Your queries should looks like

$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)");

Numbers "1,2,3,4" are post_id returned in your first question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM