如何使用' DISTINCT'在Codeigniter Active Records?

时间:2016-06-15 12:04:34

标签: php activerecord codeigniter-2

我有一个使用有效记录的查询。

$this->db->select('reg.users_id,reg.registration_id,reg.device_type');
$this->db->join('users as usr','usr.users_id = reg.users_id','left');
$this->db->where('usr.users_status',1);
$this->db->where('reg.users_id',91);
$query = $this->db->get('users_gcm_registration as reg');

我想要抓取DISTINCT(registration_id)

我该怎么做?

5 个答案:

答案 0 :(得分:11)

您可以使用distinct as

$this->db->distinct('reg.registration_id');
$this->db->select('reg.users_id,reg.device_type');
....

但最好使用group_by

$this->db->select('reg.users_id,reg.registration_id,reg.device_type');
$this->db->join('users as usr','usr.users_id = reg.users_id','left');
$this->db->where('usr.users_status',1);
$this->db->where('reg.users_id',91);
$this->db->group_by('reg.registration_id');// add group_by
$query = $this->db->get('users_gcm_registration as reg');

答案 1 :(得分:3)

只需使用$this->db->distinct();就是这样。它将明确价值......

希望它适合你...

答案 2 :(得分:2)

你有两种方法可以完成这个

  1. 以Codeigniter方式
  2. 以SQL方式
  3. Codeigniter方式

    您可以在有效记录查询中使用$this->db->distinct()

    $this->db->distinct();
    $this->db->get('table_name');
    ...
    

    以SQL方式

    $query = $this->db->query("SELECT DISTINCT * FROM table_name ...");
    $result = $query->result_array();
    return $result;
    

答案 3 :(得分:1)

iterator=True

答案 4 :(得分:1)

   $query = $this->db->select('registration_id')
                ->distinct('registration_id')
                ->from('reg')
                ->get(); 
 return $query->result();