0

我有两个表 table1 和 table2,在 table1 中我保存用户详细信息,在 table2 中他给出的评级是多行,在评级列中具有相同的 table1.id 和评级,但是当我执行以下代码时它只返回一个所有评级的行和平均值,而不是特定用户。我在查询方面有点弱,我想 Select 中需要有 Select ,但它是 CodeIgniter 所以我不能这样做。请帮忙

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

我想要的是:

> id Name  email            AvG
> 
> 1  name1 name1@xyz.com  average of ratings by this id in table2 
> 2  name2 name2@xyz.com  average of ratings by this id in table2

但我得到的是

> id  Name email           AvG
> 
> 1  name1 name1@xyz.com  average of all ratings in table2
4

1 回答 1

1

你需要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;

更新当您可以使用不考虑srating = 0的事实时获得正确的平均值。因此,您可以使用或在您的选择部分AVG()NULLIFNULL()CASE

$this->db->select('table1.id, table1.name, table1.email, AVG(NULLIF(table2.rating, 0))');

一个基本的 sql 查询应该看起来像

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
于 2013-06-12T10:11:53.733 回答