我有这个问题:
return $this->db
->select('forumCategories.id, forumCategories.name, forumCategories.order, forumCategories.date_created, COUNT(forumPosts.forumCategory_id) as postCount')
->from('forumCategories')
->join('forumPosts', 'forumCategories.id = forumPosts.forumCategory_id', 'left')
->group_by('forumPosts.forumCategory_id')
->order_by('forumCategories.order DESC')
->get()
->result_array();
查询将获取所有论坛类别并计算每个类别的帖子。问题是它只采用有帖子的类别,而且只有一个类别没有任何帖子。
示例:
Category 1 | 16 posts
Category 2 | 3 posts
Category 3 | 0 posts
Category 4 | 0 posts
Category 5 | 0 posts
Category 6 | 0 posts
仅返回类别1,2和3。如何编写此查询,以便返回所有类别?
答案 0 :(得分:1)
尝试使用始终具有值的第一个表列(forumCategories.id)进行分组。
return $this->db
->select('forumCategories.id, forumCategories.name, forumCategories.order, forumCategories.date_created, COUNT(forumPosts.forumCategory_id) as postCount')
->from('forumCategories')
->join('forumPosts', 'forumCategories.id = forumPosts.forumCategory_id', 'left')
->group_by('forumCategories.id')
->order_by('forumCategories.order DESC')
->get()
->result_array();