在 CodeIgniter 查询生成器中使用子查询编写查询?
Write query with subquery in 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->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 子句中的子查询。
不要使用 get()
后跟 last_query()
因为 get()
实际上 运行 数据库查询。
相反,使用 get_compiled_select()
将 returns 无需 运行 查询的查询。
$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()
将重置查询生成器。
我的以下查询与查询生成器有问题。
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->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 子句中的子查询。
不要使用 get()
后跟 last_query()
因为 get()
实际上 运行 数据库查询。
相反,使用 get_compiled_select()
将 returns 无需 运行 查询的查询。
$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()
将重置查询生成器。