首頁 >後端開發 >php教程 >thinkPHP簡單實作多個子查詢語句的方法

thinkPHP簡單實作多個子查詢語句的方法

不言
不言原創
2018-05-03 16:31:242799瀏覽

這篇文章主要介紹了thinkPHP簡單實現多個子查詢語句的方法,結合實例形式對比分析了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語句。

相關推薦:

thinkPHP5.0框架命名空間詳解

#################### #####

以上是thinkPHP簡單實作多個子查詢語句的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn