thinkPHP简单实现多个子查询语句的方法
程序员文章站
2024-03-05 12:28:48
本文实例讲述了thinkphp简单实现多个子查询语句的方法。分享给大家供大家参考,具体如下:
sql语句博大精深
理解好sql语句,就能用好thinkphp等框架中的数...
本文实例讲述了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 = 2015 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 = 2015 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相关内容感兴趣的读者可查看本站专题:《thinkphp入门教程》、《thinkphp模板操作技巧总结》、《thinkphp常用方法总结》、《codeigniter入门教程》、《ci(codeigniter)框架进阶教程》、《zend framework框架入门教程》、《smarty模板入门基础教程》及《php模板技术总结》。
希望本文所述对大家基于thinkphp框架的php程序设计有所帮助。
上一篇: java开发微信公众号支付
下一篇: 安卓(Android) 监听按键长按事件