tp5 使用buildSql、union
如题,SQL语句是这样的,如下所示,不用管表里内容是什么,只要知道wygl_sfgl_mxb根据条件查询出的结果与wygl_sfgl_sjjz表根据条件查出来的结果作为a表,再与b表c表左联然后再根据条件查询需要的数据,也不难,但是咱之前没这么搞过啊~~~,再说table里也不能写(SELECT yf,sfxmbh,xqh,sl,je,0 AS hs FROM wygl_sfgl_mxb WHERE je > 0 UNION ALL SELECT yf,sfxmbh,xqh,sl,je,1 AS hs FROM wygl_sfgl_sjjz WHERE je > 0)啊,写上会报错,我试过了~原生查询也不是不行,就是那么一大坨,看着就恶心,而且还要分页,SQL server的分页到现在也没弄明白怎么回事,我也不想弄明白~~~最后在度娘的领导下,经过CSDN,博客园的不懈努力………,终于,找到了正确的写法,如下
$sql1 = Db::connect($this->config)->table('wygl_sfgl_mxb')->field('yf,sfxmbh,xqh,sl,je,0 AS hs')->where('je', '>','0')->buildSql(); $sql3 = Db::connect($this->config)->table('wygl_sfgl_sjjz')->field('yf,sfxmbh,xqh,sl,je,1 AS hs')->where('je','>','0')->union([$sql1])->buildSql(); $res = Db::connect($this->config) ->table($sql3) ->alias('a') ->leftJoin('wygl_sfxm b','a.sfxmbh= b.dm') ->leftJoin('sys_qx_sjqx qx','a.xqh= qx.xmdm') ->field('a.yf,a.sfxmbh,b.mc,COUNT ( 1 ) AS yshs,SUM ( a.sl ) AS yssl,SUM ( a.je ) AS ysje,SUM ( a.hs ) AS yishs,SUM ( a.hs* a.sl ) yissl,SUM ( a.hs* a.je ) AS yisje,SUM ( a.hs- 1 ) * ( - 1 ) AS wshs,SUM ( ( a.hs- 1 ) * a.sl ) * ( - 1 ) AS wssl,SUM ( ( a.hs- 1 ) * a.je ) * ( - 1 ) AS wsje ') ->where($map) ->group('a.yf ,a.sfxmbh,b.mc') ->order(["yf"=>"desc","sfxmbh","mc"]) ->paginate(20);
上面是解决的tp5写法,下面是原始SQL语句,数据库背景是SQL server。
SELECT TOP 100 a.yf, b.mc, COUNT ( 1 ) AS yshs, SUM ( a.sl ) AS yssl, SUM ( a.je ) AS ysje, SUM ( a.hs ) AS yishs, SUM ( a.hs* a.sl ) yissl, SUM ( a.hs* a.je ) AS yisje, SUM ( a.hs- 1 ) * ( - 1 ) AS wshs, SUM ( ( a.hs- 1 ) * a.sl ) * ( - 1 ) AS wssl, SUM ( ( a.hs- 1 ) * a.je ) * ( - 1 ) AS wsje FROM (SELECT yf,sfxmbh,xqh,sl,je,0 AS hs FROM wygl_sfgl_mxb WHERE je > 0 UNION ALL SELECT yf,sfxmbh,xqh,sl,je,1 AS hs FROM wygl_sfgl_sjjz WHERE je > 0 ) a LEFT OUTER JOIN wygl_sfxm b ON a.sfxmbh= b.dm LEFT OUTER JOIN sys_qx_sjqx qx ON a.xqh= qx.xmdm WHERE a.yf>= '19700101' AND a.yf <= '20200917' AND qx.flag= 1 AND qx.dm= '1003' GROUP BY a.yf , a.sfxmbh, b.mc ORDER BY a.yf DESC, a.sfxmbh, b.mc