select all comments with all posts php mysql

二次信任 提交于 2020-01-06 19:35:27

问题


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 ?


回答1:


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.



来源:https://stackoverflow.com/questions/27806127/select-all-comments-with-all-posts-php-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!