2013-01-10 57 views
1

我目前從我的'social_posts'表中獲取詳細信息,然後添加它的標籤,喜歡的數量以及它對結果對象的答案數量。有沒有辦法可以做到這一點,而不必在循環中做額外的查詢?安排JOIN數據庫結果

$query = "SELECT * FROM social_posts JOIN users ON social_posts.user_id = users.id"; 
    $posts = $this->db->query($query); 

    if ($posts->num_rows() > 0) {   
     foreach ($posts->result() as $p => $post) {      
      // Get the question's tags 
      $tags = $this->db->query("SELECT * FROM social_tags 
       WHERE post_id = ?", $post->post_id); 

      // Get the number of likes 
      $likes = $this->db->query("SELECT id FROM social_likes 
       WHERE post_id = ?", $post->post_id); 

      // Get the number of answers 
      $answers = $this->db->query("SELECT id FROM social_responses 
       WHERE post_id = ?", $post->post_id); 

      $post->tags = $tags->result(); 
      $post->likes = $likes->num_rows(); 
      $post->answers = $answers->num_rows(); 
      $post->author = array(
       "firstname" => $post->firstname, 
       "thumbnail" => $post->thumbnail, 
      ); 
     } 

     return $posts->result(); 
    } else { 
     return FALSE; 
    } 

回答

2

你可以試試這個SQL:

SELECT 
    social_posts.*, 
    users.*, 
    GROUP_CONCAT(social_tags.name) AS tags, 
    COUNT(social_likes.id) AS likes, 
    COUNT(social_responses.id) AS answers 
FROM 
    social_posts 
     JOIN users ON social_posts.user_id = users.id 
     LEFT JOIN social_tags ON social_tags.post_id = social_posts.id 
     LEFT JOIN social_likes ON social_likes.post_id = social_posts.id 
     LEFT JOIN social_responses ON social_responses.post_id = social_posts.id 
GROUP BY 
    social_posts.id 

您將獲得的標籤,逗號分隔的字符串。當然,您需要調整列名以適合您的數據庫。

+0

非常感謝,這太棒了!它似乎沒有顯示任何回覆的帖子,但?我在哪裏指定「WHERE」子句? – Sneaksta

+0

1)在您的原始代碼中,據我所知,您只能得到響應的數量。爲後續查詢獲取給定帖子的所有回覆可能是一個更好的主意,因爲可能需要更多來自social_responses表的列。 – oujesky

+1

2)WHERE子句在FROM和GROUP BY子句之間獲取 – oujesky