使用CodeIgniter中的连接选择具有特定行值平均值的特定列

时间:2013-06-12 10:04:31

标签: mysql codeigniter

我有两个表table1和table2,在table1中我保存了用户详细信息,在table2中他给出的评级是多行,在rating列中有相同的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

1 个答案:

答案 0 :(得分: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;

更新要在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