我有以下查询,其中包含查询生成器的问题。
SELECT Sum(TEMP.total) AS total_amount
FROM (SELECT Ifnull(t3.amount, t1.amount) AS total
FROM table1 AS t1
LEFT JOIN table2 AS t2
ON t2.class = t1.class
LEFT JOIN table3 AS t3
ON t3.student = t2.student
AND t3.type = t1.type) AS TEMP
有没有办法用Query Builder做到这一点?我目前正在使用this方法。
不要使用get()
,然后使用last_query()
,因为get()
实际上会在数据库上运行查询。
相反,使用get_compiled_select()
将返回查询而不运行它。
$this->db->select('IFNULL(t3.amount, t1.amount) as total');
$this->db->from('table1 as t1');
$this->db->join('table2 as t2', 't2.class = t1.class', 'LEFT');
$this->db->join('table3 as t3', 't3.student = t2.student AND t3.type = t1.type', 'LEFT');
$subquery = $this->db->get_compiled_select();
$this->db->select('SUM(TEMP.total) as total_amount');
$this->db->from('('.$subquery.') as TEMP');
$result = $this->db->get()->result_array();
默认情况下,get_compiled_select()
将重置查询构建器。
请仔细检查,希望对您有所帮助
$this->db->select('IFNULL(t3.amount, t1.amount) as total');
$this->db->from('table1 as t1');
$this->db->join('table2 as t2', 't2.class = t1.class', 'LEFT');
$this->db->join('table3 as t3', 't3.student = t2.student AND t3.type = t1.type', 'LEFT');
// $this->db->get();
$lastquery = $this->db->last_query();
$this->db->select('SUM(TEMP.total) as total_amount');
$this->db->from('('.$lastquery.') as TEMP');
$result = $this->db->get()->result_array();
如果您的mysql查询没问题,请使用此方法运行这样的复杂查询。
$sql = "Your Query";
$qr = $this->db->query($sql);
return $qr->row();
如果您仍未获得输出,请首先在from子句中检查子查询。