1

I have two tables company,rate

Company has two columns-

  • v_id
  • company_name

user_ratings has three columns

  • r_id
  • v_id
  • rate

In this rate v_id column,I have company_id (v_id) which has two different rating and when i count the ratings for one company every time i am getting only one. How to count the ratings for company.

function get_list() {

        $this->db->select('company.company_name, COUNT(user_ratings.rate) as rate');
        $this->db->from('company_details');
        $this->db->join('user_ratings', 'company.v_id = user_ratings.v_id');
        $this->db->group_by('company.company_name, rate');
        $query = $this->db->get();

        return  $query->result();
    }
2
  • Its return only one record from user rating table because of goup_by..try after removing group by Commented Apr 17, 2017 at 12:47
  • after removing group by i am getting error like In aggregated query without GROUP BY Commented Apr 17, 2017 at 12:57

1 Answer 1

1

You have grouped results with both company_name and rate. This is why it's returning count as 1 for all records. Grouping only by company name will return desired results.

Change this

$this->db->group_by('company.company_name, rate');

to

$this->db->group_by('company.company_name');

Also, company is used as an alias for company_details table but its not created.

$this->db->from('company_details AS company');
Sign up to request clarification or add additional context in comments.

5 Comments

It's giving proper data. sqlfiddle.com/#!9/757778/2. For company ID 3 there is only 1 rating, so rate value is 1. For company ID 1 there are 2 ratings, so rate value is 2.
i am little bit shocked, Because this query is running on sqlfiddle But on mysql this query is throwing error.
Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'search.company.v_id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
Remove sql mode (FULL_GROUP_BY) from your sql config file
Thank You Guys.. i Don't need to remove (FULL_GROUP_BY) .

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.