ThinkPHP多子查询SQL实现指南
本示例详细讲解了如何在ThinkPHP中简便地处理多个子查询语句的逻辑,供读者参考借鉴。
SQL语言体系庞大且深奥。
深入理解SQL原理,有助于熟练运用ThinkPHP等框架内的数据库交互功能。
原始SQL代码如下:
SELECT a.*,b.* from (SELECT a.id as opener_id,a.name,sum(c.money) as bonus_money,c.year,c.month from sh_opener a
LEFT JOIN sh_opener_bonus b on a.id = b.opener_id
LEFT JOIN sh_incentive c on b.incentive_id = c.id
where a.agent_id = 3 and a.status = 1 and c.year = 2026 and c.month = 11
GROUP BY a.id,c.year,c.month) a
LEFT JOIN (SELECT a.id as payment_id,a.opener_id,a.money as payment_money,a.trode_number from sh_opener_bonus_payment a
where a.year = 2026 and a.`month` = 11 and a.agent_id = 3) b
on a.opener_id = b.opener_id;
该查询包含两个子查询部分。本质上,子查询生成的结果集被视为一张临时表,仅存在于内存中。
使用ThinkPHP进行实现的步骤如下:
$useYear = date('Y',strtotime('last month'));
$this->assign('useYear',$useYear);
$useMonth = date('m',strtotime('last month'));
$this->assign('useMonth',$useMonth);
// 获取上一月人员的奖金金额
// 子查询1
$whereSub1['a.agent_id'] = $this->agent_id;
$whereSub1['a.status'] = 1;
$whereSub1['c.year'] = $useYear;
$whereSub1['c.month'] = $useMonth;
$subQuery1 = M()->table('sh_opener a')->join('sh_opener_bonus b on a.id = b.opener_id')->join('sh_incentive c on b.incentive_id = c.id')->where($whereSub1)->group('a.id,c.year,c.month')->field('a.id,a.name,sum(c.money) as bonus_money,c.year,c.month')->select(false);
// 子查询2
$whereSub2['a.agent_id'] = $this->agent_id;
$whereSub2['a.year'] = $useYear;
$whereSub2['a.month'] = $useMonth;
$subQuery2 = M()->table('sh_opener_bonus_payment a')->where($whereSub2)->field('a.id as payment_id,a.opener_id,a.money as payment_money,a.trode_number')->select(false);
$list = M()->table($subQuery1.' a')->join($subQuery2.' b on a.id = b.opener_id')->select();
$this->assign('list',$list);
尽管ThinkPHP对SQL进行了面向对象式的封装,但其底层逻辑依然依赖于最终拼接成标准的SQL字符串。
期望上述内容能为基于ThinkPHP框架进行PHP开发的程序员提供有价值的参考。