在CodeIgniter查询生成器中使用子查询编写查询?

时间:2019-04-11 09:10:43

标签: php codeigniter query-builder

我有以下查询,查询生成器有问题。

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 

使用查询生成器有什么方法吗?我当前正在使用this方法。

3 个答案:

答案 0 :(得分:2)

请对此进行检查,希望对您有帮助

$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();

答案 1 :(得分:1)

请勿使用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()将重置查询生成器。

See the docs

答案 2 :(得分:0)

如果您的mysql查询正常,请使用这种方法来运行类似这样的复杂查询。

$sql = "Your Query";
$qr = $this->db->query($sql);
return $qr->row();

如果仍然没有得到输出,请首先在from子句中检查子查询。