CodeIgniter:在CodeIgniter中使用group_by

时间:2013-10-07 16:35:47

标签: codeigniter activerecord

我有一个带有“用户名”和“帖子”的数据库。如何使用CodeIgniter db class获取每个用户名的帖子数?

在SQL中:

SELECT 
  user_name, 
  COUNT(1) as post_count
FROM posts_by_user
GROUP BY user_name

在CodeIgniter中:

$this->db->select('user_name', ???????);
$this->db->from('posts_by_user');
$this->db->group_by('user_name');
$result = $this->db->query();

1 个答案:

答案 0 :(得分:1)

尝试

$this->db->select('user_name, COUNT(*) as cnt', FALSE);
$this->db->from('posts_by_user');
$this->db->group_by('user_name');
$result = $this->db->get();

return $result->result();