0

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

1 Answer 1

1

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 NULLs. 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
Sign up to request clarification or add additional context in comments.

8 Comments

thank you so much, now I am 100% sure I am very bad at SQL.. thank you so much
peterm, hi can you tell me if there is any way if table2.rating =0, it doesnot get included in average ?
@Deepanshu You are welcome. And see updated answer for your additional question.
@Deepanshu Updated the answer. Sorry, typo. Forgot closing parentheses for NULLIF(). Try it again with parentheses.
@Deepanshu Try execute SQL query directly in myphpadmin with exact where conditions and see if you get correct results.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.