我有两个表table1和table2,在table1中,我保存了用户详细信息,在table2中,他给出的评级是具有相同table1.id和rating列中评级的多行,但是当我执行以下代码时,它仅返回一个所有评分的行和平均值,而不是特定用户。我的查询能力不强,我猜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

最佳答案

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


更新要获得rating = 0时的正确平均值,您可以使用AVG()不考虑NULL的事实。因此,可以在选择的部分中使用IFNULL()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

10-05 21:06
查看更多