Php 排列联接数据库结果

Php 排列联接数据库结果,php,mysql,codeigniter,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_row

我目前正在从我的“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;
    }
您可以尝试以下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

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

非常感谢,这太棒了!但它似乎没有显示任何对帖子的回复?我应该在哪里指定“where”子句呢?1)在您的原始代码中,据我所知,您只得到了响应的数量。可能更好的办法是进行后续查询,以获取给定帖子的所有回复,因为您可能希望从social_responses表中获得更多列。2)WHERE子句介于from和GROUP BY之间。您的说法是正确的,我只需要回复的计数,对不起。我在应用程序中看到了一个不同的函数,弄糊涂了。我想我已经把它整理好了。谢谢!组_CONCAT(DISTINCT social_tags.name)应该可以工作,请查看