如何编写此子查询在Codeigniter中选择具有限制的AVG

时间:2018-09-10 12:27:37

标签: mysql codeigniter subquery

SELECT AVG(harian) a from (select harian from sla limit 2) b

以上工作在Heidisql中执行,

并在下面尝试过

$rata2 = $this->db->query('SELECT AVG(harian) a from (select harian from sla limit 2) b');

但是,似乎没有输出,请帮助,谢谢

1 个答案:

答案 0 :(得分:0)

// Sub Query
$this->db->select('harian')->from('sla')->limit(2);
$subQuery =  $this->db->get_compiled_select();

// Main Query
$rata2 = $this->db->select('AVG(harian)')
     ->from($subQuery)
     ->get();

return $rata2; 

或者如果您想返回数组中的数据

// Sub Query
$this->db->select('harian')->from('sla')->limit(2);
$subQuery =  $this->db->get_compiled_select();

// Main Query
$rata2 = $this->db->select('AVG(harian)')
     ->from($subQuery)
     ->get()
     ->toArray();

return $rata2;