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

PhpMysqlCodeigniterDistinct

Php Problem Overview


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.

Php Solutions


Solution 1 - Php

$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.

Solution 2 - Php

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();  
}

Solution 3 - Php

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`

Solution 4 - Php

Simple but usefull way:

$query = $this->db->distinct()->select('order_id')->get_where('tbl_order_details', array('seller_id' => $seller_id));
        return $query;

Solution 5 - Php

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIanView Question on Stackoverflow
Solution 1 - PhpMark UnwinView Answer on Stackoverflow
Solution 2 - PhpuseranonView Answer on Stackoverflow
Solution 3 - PhpjonwayneView Answer on Stackoverflow
Solution 4 - PhpSani KamalView Answer on Stackoverflow
Solution 5 - PhpjoashView Answer on Stackoverflow