php - Write query with subquery in CodeIgniter Query Builder?
问题描述
I have the following query which has an issue with 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
Is there any way to do it with Query Builder? I'm currently using this method.
解决方案
DO NOT USEget()
后跟,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()
将重置查询生成器。
推荐阅读
- angular - 传输超时太短导致 Angular Socket.IO Web 套接字在连接建立之前关闭
- python - 在相同图形上绘制不同模型的 roc 曲线
- oracle - (Oracle)打开视图时显示权限不足
- sql - 孩子的递归总和以计算oracle 12c中的另一个字段
- outlook - 在 Outlook 中,更改 POP3 服务器设置会删除现有的收件箱电子邮件吗?
- sas - 为什么错误的内部查询不会使外部查询错误
- javascript - 我的表中有两个唯一键。使用异常 DUP_VAL_ON_INDEX 时,我可以选择发生违规的特定(唯一)列吗?
- python - 使用 jinja 标签在 html 标签内使用 if 条件
- python - 装饰类的方法会导致 2.7 中的未绑定方法 TypeError
- sql - 无法连接到 docker 容器内的 SQL Server