2013-04-30 114 views
1

我正在使用Codeigniter,並試圖爲我所有的數據庫操作使用Active Record Class。如何在Codeigniter Active Record中使用SQL COUNT(DISTINCT column_name)函數編寫HAVING子句?

但是,在嘗試將以下(工作)查詢的最後一次出價轉換爲Active Record代碼時遇到了問題。

$sql = ("SELECT ac.cou_id 
     FROM authorcourse ac 
     INNER JOIN course c 
     ON ac.cou_id = c.cou_id 
     WHERE cou_name = ? // ? = $cou_name 
     AND cou_number = ? // ? = $cou_number 
     AND cou_term = ? // ? = $cou_term 
     AND cou_year = ? // ? = $cou_year 
     AND FIND_IN_SET (ac.aut_id, ?) //? = $aut_ids_string 
     GROUP BY ac.cou_id 
     HAVING COUNT(DISTINCT ac.aut_id) = ? //? = $aut_quantity 
     AND COUNT(DISTINCT ac.aut_id) = (SELECT COUNT(DISTINCT ac2.aut_id) 
              FROM authorcourse ac2 
              WHERE ac2.cou_id = ac.cou_id)"); 
$query = $this->db->query($sql, array($cou_name, $cou_number, $cou_term, $cou_year, $aut_ids_string, $aut_quantity)); 

問題:如何轉換HAVING子句爲有效的活動記錄代碼? 我試過使用$ this-> db-> having();和$ this-> db-> distinct();但未能將這些功能結合起來以達到預期的效果。

我的(工作)到目前爲止的代碼:

$this->db->select('ac.cou_id'); 
$this->db->from('authorcourse ac'); 
$this->db->join('course c', 'c.cou_id = ac.cou_id'); 
$this->db->where('cou_name', $cou_name); 
$this->db->where('cou_number', $cou_number); 
$this->db->where('cou_term', $cou_term); 
$this->db->where('cou_year', $cou_year); 
$this->db->where_in('ac.aut_id',$aut_ids); 
$this->db->group_by('ac.cou_id'); 
// missing code 

非常感謝!

回答

0

你的代碼看起來很笨拙。但是,你可以使用以下方式having子句:

$this->db->having("ac.aut_id = '".$aut_qty."'", null, false) 
+1

如果這個工作在所有的,我很擔心,這將是容易受到SQL注入,因爲CI_DB_active_record不會通過推用戶提供的數據CI_DB_driver.escape(),因爲它全部在$ k而不是$ v。 – Cheekysoft 2013-05-02 09:39:58

+1

謝謝你的迴應,Veekay。但是,這並不回答我的問題(如何將HAVING COUNT(DISTINCT ac.aut_id)=?...轉換爲有效的活動記錄代碼)。 – user1894374 2013-05-04 08:49:32

相關問題