Mysql
 sql >> Database >  >> RDS >> Mysql

Come ottenere l'elenco dei post e i tag associati con il minor numero di query

Se indicizzi $tagsResult per postId , che puoi fare utilizzando FETCH_GROUP , quindi puoi rimuovere il ciclo nidificato interno e acquisire tutti i tag con un determinato postId in un tempo costante:

$sql = "
    SELECT pt.idPost, — select idPost first so it’s grouped by this col
           t.*
      FROM tags t JOIN poststags pt ON t.id=pt.idTag 
     WHERE pt.idPost IN (array of post ids)
";

$stmt=$db->prepare($sql);
$stmt->execute();

$tagsResult = $smt->fetchAll(\PDO::FETCH_GROUP|\PDO::FETCH_OBJ);
//$tagsResult is now grouped by postId
//see https://stackoverflow.com/questions/5361716/is-there-a-way-to-fetch-associative-array-grouped-by-the-values-of-a-specified-c

foreach($postsResult as &$post) {

    if(isset($tagsResult[$post->id])) {
        $post->tags = $tagsResult[$post->id];
    }
    else {
        $post->tags = array();
    }   
}