2013-06-12 44 views
0

我在Table1中有兩個表table1和table2我保存用戶的詳細信息,並在table2中給出了他給出的具有相同table1.id的多行的等級和評分欄中的評分,但是當我執行下面的代碼時,它只返回所有評分的一行和平均值,而不是特定用戶。我在查詢方面有點弱,我猜這裏需要在Select中選擇,但它是CodeIgniter,所以我無法做到這一點。請幫助使用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 [email protected] average of ratings by this id in table2 
> 2 name2 [email protected] average of ratings by this id in table2 

,但我所得到的是

> id Name email   AvG 
> 
> 1 name1 [email protected] average of all ratings in table2 

回答

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; 

UPDATE爲了得到正確的平均值,當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 
+0

太感謝你了,現在我100%肯定,我非常糟糕的SQL ..非常感謝你 –

+0

peterm,你好你能告訴我,如果有任何方式,如果table2.rating = 0,它不包括平均? –

+0

@Deepanshu不客氣。並看到更新的答案爲您的額外問題。 – peterm

相關問題