找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 1655|回复: 0
打印 上一主题 下一主题

thinkPHP简单实现多个子查询语句的方法

[复制链接]

2487

主题

2487

帖子

7391

积分

论坛元老

Rank: 8Rank: 8

积分
7391
跳转到指定楼层
楼主
发表于 2018-2-14 05:29:56 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式

            本文实例讲述了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程序设计有所帮助。
            
            
您可能感兴趣的文章:
  • thinkphp3查询mssql数据库乱码解决方法分享
  • 浅析ThinkPHP中execute和query方法的区别
  • ThinkPHP之getField详解
  • Thinkphp使用mongodb数据库实现多条件查询方法
  • ThinkPHP查询语句与关联查询用法实例
  • thinkphp数据查询和遍历数组实例
  • ThinkPHP采用原生query实现关联查询left join实例
  • thinkphp中多表查询中防止数据重复的sql语句(必看)
  • Thinkphp连表查询及数据导出方法示例
  • thinkPHP实现多字段模糊匹配查询的方法
  • thinkPHP数据查询常用方法总结【select,find,getField,query】
            
  • 分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
    收藏收藏
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    用户反馈
    客户端