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

來源:互聯網
上載者:User
這篇文章主要介紹了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 aLEFT JOIN sh_opener_bonus b on a.id = b.opener_idLEFT JOIN sh_incentive c on b.incentive_id = c.idwhere a.agent_id = 3 and a.status = 1 and c.year = 2015 and c.month = 11GROUP BY a.id,c.year,c.month) aLEFT JOIN (SELECT a.id as payment_id,a.opener_id,a.money as payment_money,a.trode_number from sh_opener_bonus_payment awhere a.year = 2015 and a.`month` = 11 and a.agent_id = 3) bon 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語句。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.