CodeIgniter: How To Do a Select (Distinct Fieldname) MySQL Query


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.

12/31/2011 10:24:39 AM

Accepted Answer

$record = '123';



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

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



should go a long way towards it.

5/16/2013 2:15:47 AM

You can also run ->select('DISTINCT `field`', FALSE) and the second parameter tells CI not to escape the first argument. With the second parameter the output would be SELECT DISTINCT `field` instead of without the second parameter, SELECT `DISTINCT` `field`

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow