1

我目前正在从我的“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;
    }
4

1 回答 1

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

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

于 2013-01-10T00:49:45.397 回答