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.
To get unique or distinct values of a column in MySQL Table, use the following SQL Query. SELECT DISTINCT(column_name) FROM your_table_name; You can select distinct values for one or more columns. The column names has to be separated with comma.
You can use below mentioned query. $query = $this->db->group_by('category_master. Category_Id,business_profile_details. Business_Id');
By using the WHERE clause with a DISTINCT clause in MySQL queries, we are putting a condition on the basis of which MySQL returns the unique rows of the result set.
We can use the MySQL DISTINCT clause to return a single field that removes the duplicates from the result set. For example: SELECT DISTINCT state FROM customers; This MySQL DISTINCT example would return all unique state values from the customers table.
$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.
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With