55

I'm trying to retrieve a count of all unique values in a field.

Example SQL:

SELECT count(distinct accessid) FROM (`accesslog`) WHERE record = '123'

How can I do this kind of query inside of CodeIgniter?

I know I can use $this->db->query(), and write my own SQL query, but I have other requirements that I want to use $this->db->where() for. If I use ->query() though I have to write the whole query myself.

imlouisrussell
  • 936
  • 11
  • 30
Ian
  • 11,920
  • 27
  • 61
  • 77

5 Answers5

118
$record = '123';

$this->db->distinct();

$this->db->select('accessid');

$this->db->where('record', $record); 

$query = $this->db->get('accesslog');

then

$query->num_rows();

should go a long way towards it.

bart_88
  • 488
  • 2
  • 4
  • 15
Mark Unwin
  • 1,613
  • 1
  • 15
  • 19
12

You can also run ->select('DISTINCT `field`', FALSE) and the second parameter tells CI not to escape the first argument.

With the second parameter as false, the output would be SELECT DISTINCT `field` instead of without the second parameter, SELECT `DISTINCT` `field`

sauhardnc
  • 1,961
  • 2
  • 6
  • 16
jonwayne
  • 483
  • 5
  • 9
12

try it out with the following code

function fun1()  
{  
   $this->db->select('count(DISTINCT(accessid))');  
   $this->db->from('accesslog');  
   $this->db->where('record =','123');  
   $query=$this->db->get();  
   return $query->num_rows();  
}
VxJasonxV
  • 951
  • 11
  • 35
useranon
  • 29,318
  • 31
  • 98
  • 146
6

Simple but usefull way:

$query = $this->db->distinct()->select('order_id')->get_where('tbl_order_details', array('seller_id' => $seller_id));
        return $query;
Sani Kamal
  • 1,208
  • 16
  • 26
5

Since the count is the intended final value, in your query pass

$this->db->distinct();
$this->db->select('accessid');
$this->db->where('record', $record); 
$query = $this->db->get()->result_array();
return count($query);

The count the retuned value

joash
  • 2,205
  • 2
  • 26
  • 31