如何在Codeigniter Active Record中使用SQL COUNT(DISTINCT column_name)函数编写HAVING子句?

时间:2013-04-30 12:38:26

标签: sql codeigniter activerecord count having-clause

我正在使用Codeigniter,并尝试将Active Record Class用于我的所有数据库操作。

但是,在尝试将以下(工作)查询的最后出价转换为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子句转换为有效的Active Record代码? 我尝试使用$ 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

非常感谢!

1 个答案:

答案 0 :(得分:0)

你的代码看起来很笨拙。但是,您可以通过以下方式使用having子句:

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