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.
Solution 1:
$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:
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:
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:
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:
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