Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 759
Ian Avatar asked Mar 18 '09 01:03

Ian


People also ask

How do I select distinct data in MySQL?

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.

How use distinct in join query in Codeigniter?

You can use below mentioned query. $query = $this->db->group_by('category_master. Category_Id,business_profile_details. Business_Id');

Can I use distinct in where clause MySQL?

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.

What is distinct in MySQL with example?

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.


2 Answers

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

like image 199
Mark Unwin Avatar answered Oct 26 '22 00:10

Mark Unwin


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();   } 
like image 40
useranon Avatar answered Oct 26 '22 00:10

useranon