zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    如何使用yum来下载RPM包而不进行安装
    mysqlbinlog工具基于日志恢复详细解释
    mysql 误删除ibdata1之后如何恢复
    MariaDB Galera Cluster 部署(如何快速部署MariaDB集群)
    利用MariaDB Galera Cluster实现mariadb的多主复制
    PHP-Java-Bridge使用笔记,2014年9月最新版
    PHP-Java-Bridge的使用(平安银行支付功能专版)
    初识layer 快速入门
    CSS 的class属性居然可以并(有点像并,有点像与)操作
    jquery的监听事件和触发事件
  • 原文地址:https://www.cnblogs.com/dayin1/p/13685648.html
Copyright © 2011-2022 走看看