问题
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