mysql tp5关联查询DB,一对多

发布时间:2020-01-19作者:小灵龙点击:108

问题描述:
     一个admin表,字段id,zhandian_id;一个用户积分表,字段user_id;一个商品表,字段site_id。他们的关系是:site_id=zhandian_id,id=user_id。需求是查询各个站点的所有员工在时间段内的成交总额和所产生的积分、站点的所有员工的剩余积分

解决办法:
方法一:


         $list=Db::name("admin")->alias('ad')

        ->where('ad.is_work',1)

         ->where('ad.zhandian_id','not null')

        ->group('ad.zhandian_id')

        ->field('ad.zhandian_id,sum(ad.integral) as shengyujifen,
                (
            select sum(order_price)
            from gczywxcx_order
            where site_id = ad.zhandian_id
                and `order_state` = 2
                AND `is_type` = 3
                AND `confirm_date` BETWEEN '.strtotime($k3.'00:00:00').'  AND '.strtotime($k4.'23:59:59').'
        ) as sumPrice,(
            select sum(fee)
            from gczyadmin_integlog
            where user_id in (select id from gczyc_admin where zhandian_id = ad.zhandian_id)
                AND `type` = 1
                AND `add_date` BETWEEN '.strtotime($k3.'00:00:00').' 
                  AND '.strtotime($k4.'23:59:59').'
        ) as chanfen)
               ->order('sumPrice','desc')
               ->select();

方法二:
             $list=Db::name('admin_integlog')->alias('inte')
        ->join('admin ad','ad.id=inte.user_id')
        ->group('ad.zhandian_id')
        ->field('ad.zhandian_id,

            sum(if(type=1 and inte.add_date BETWEEN '.strtotime($k3.'00:00:00').' AND '.strtotime($k4.'24:00:00').' , inte.fee,0)) as chanfen,

            (SELECT sum( order_price ) FROM gczyc_wxcx_order WHERE site_id = ad.zhandian_id AND `order_state` = 2 AND `is_type` = 3    AND `confirm_date` BETWEEN '.strtotime($k3.'00:00:00').' AND '.strtotime($k4.'24:00:00').') as sumPrice ,

            sum(inte.fee) as leijifen,           

            sum(if(type=0, inte.fee,0)) as leijiyongfen,           

            sum(if(type=1, inte.fee,0)) as leijichan,

            sum(if(type=2, inte.fee,0)) as leijiyi,

            sum(if(type=3, inte.fee,0)) as cancelorder

            ,(select description from gczyc_jiayouzhan jia where id=ad.zhandian_id ) as description'

        )

        ->select();

标签: