Reputation: 2823
I have two tables table1 and table2, in table1 I am saving the user details and in table2 the ratings he has given which are multiple rows with same table1.id and ratings in rating column, but when I execute the following code it returns only one row and average of all the ratings instead of the specific user. I am little weak at queries, I guess there needs to be Select within Select , but it is CodeIgniter so am not able to do that. Please help
$this->db->select('table1.id,table1.name, table1.email, AVG(table2.rating)');
$this->db->from('table1');
$this->db->join('table2', 'table1.id = table2.review_id', 'inner');
$this->db->where(array('table1.status' => 1, 'table1.b_id' => $bid));
$query = $this->db->get();
return $query;
What I want is :
> id Name email AvG
>
> 1 name1 [email protected] average of ratings by this id in table2
> 2 name2 [email protected] average of ratings by this id in table2
but what I am getting is
> id Name email AvG
>
> 1 name1 [email protected] average of all ratings in table2
Upvotes: 0
Views: 2031
Reputation: 92805
You need GROUP BY
$this->db->select('table1.id, table1.name, table1.email, AVG(table2.rating)');
$this->db->from('table1');
$this->db->join('table2', 'table1.id = table2.review_id', 'inner');
$this->db->where(array('table1.status' => 1, 'table1.b_id' => $bid));
$this->db->group_by(array('table1.id','table1.name', 'table1.email'));
$query = $this->db->get();
return $query;
UPDATE To get correct average when rating = 0
you can use the fact that AVG()
doesn't take into account NULL
s. Therefore you can use IFNULL()
or CASE
in your select part
$this->db->select('table1.id, table1.name, table1.email, AVG(NULLIF(table2.rating, 0))');
A base sql query should look like
SELECT t1.id, t1.name, t1.email, AVG(NULLIF(t2.rating, 0)) rating
FROM table1 t1 JOIN table2 t2
ON t1.id = t2.review_id
WHERE ...
GROUP BY t1.id, t1.name, t1.email
Upvotes: 1