排列JOIN数据库结果

时间:2013-01-10 00:22:50

标签: php mysql codeigniter

我目前正从我的'social_posts'表中获取详细信息,然后添加它的标签,喜欢的数量以及它对结果对象的答案数量。有没有办法我可以这样做而不必在循环中进行额外的查询?

    $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;
    }

1 个答案:

答案 0 :(得分: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

您将获得标记为逗号分隔的字符串。当然,您需要调整列名以适合您的数据库。