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语句。

 

转载于:https://www.cnblogs.com/jiqing9006/p/5021968.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值