Looping through MySQL left join in php vs. 2 separate queries

萝らか妹 提交于 2019-12-04 19:29:29

One query is fine. As you have it, and probably the better opton. You have to work out which is more efficient, to let MySQL take the strain, or the network and PHP take the strain. It's a lot better to let PHP take the strain than MySQL, but where MySQL has "inbuilt" features, such as the grouping you desire, then leave the MySQL and save the network traffic.

To make this work: add "ORDER BY p.post_id, pc.comment_id" to your query - this gets the results in order.

Then, if you must build into an array (although you may be able to process directly without using an array, the method would be similar):

$lastPostID = 0;
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    if ($lastPostID <> $row['post_id']) {
        $lastPostID  = $row['post_id'];
        $answers[$lastPostID] = array('post_id' => $row['post_id'],
                                      'author_id' => $row['author_id'],
                                      etc
                                      'comments' => array() );
    }
    $answers[$lastPostID]['comments'][] = array('comment_id' => $row['comment_id'], 'coment' => $row['comment'] etc);
}

The choice is yours. Each has their advantages and drawbacks. Using a single query, (obviously, single database call and) you only need to loop over your data set once, but you have the potential of returning duplicated data. Using multiple queries, you have only pull back exactly the data you need, but (obviously, multiple database calls and) you have to iterate over multiple sets of data.

Below is a dirty implementation of the single query method (same basic flow applies to the multi-query method except comment building is it's own loop). But the basic idea is there. You have a map of your answers, adding/retrieving them as you iterate the records, and appending the comments.

while ($answers = $stmt->fetch(PDO::FETCH_ASSOC)) 
{
    $post_id = strval($answers['post_id']);
    if(!array_key_exists($post_id, $answers_array)) {
        $answers_array[$post_id] = array(
            'post_id' => $answers['post_id'],
            // ... assign other stuff ...
            'comments' => array()); //initialize the comments array
    }
    if(!empty($answers_array['comment_id'])) {
        $obj = $answers_array[$post_id];
        $obj['comments'][] = array(
            'comment_id' => $answers['comment_id'], 
            'comment_content' => $answers['comment_content']);
    }
}

You'll want to use a JOIN to return all the results with a single query, otherwise, you'll be making multiple queries, one for each post. You'd have a lot of overhead by issuing many separate queries.

An exception would be if you wanted to return a very small number of post results.

Be sure to ORDER the query by post_id, comment_id.

To iterate through the combined results, it would look something like this:

$post_id = 0;
foreach($rows as $row) {
  // See if our post changed
  if ($post_id != $row['post_id']) {
    // Display the post and post header
    ..
    // Update the current post_id variable
    $post_id = $row['post_id'];
  }
  // Display the comment
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!