mysql if对数据进行处理 having对数据进行查询 thinkphp中的exp支持更复杂的where查询...

很多时候,数据库获取的信息并不是我们最终想要的,需要通过if进行处理。

where支持查询

having支持后查询(查询后的数据,再筛选)

代码如下:

if ($this->_post('dosearch','isset')) { // 搜索
            if ($s_name = $this->_post('s_name','isset')) {
                $where['a.name'] = array('like','%'.$s_name.'%');
                $this->assign('s_name',$s_name);
            }

            if ($s_category = $this->_post('s_category','isset')) {
                $where['a.category_id'] = $s_category;
                $this->assign('s_category',$s_category);
            }

            if ($s_status = $this->_post('s_status','isset')) {
                $having ='status ='.$s_status; // 只支持字符串
                $this->assign('s_status',$s_status);
            }
        }

if

// 获取商铺
        $subQuery = M('User')->where(array('agent_id'=>$this->agent_id,'status'=>1))
                             ->field('id')
                             ->select(false);
        $where['a.user_id'] = array('exp','in '.$subQuery);
        $where['a.status'] = 1;
        $list       = M()->table('sh_store a')
                    ->join('sh_goods b on a.id = b.store_id')
                    ->join('sh_category c on a.category_id = c.id')
                    ->join('sh_mall_shop d on a.id = d.store_id and d.mall_id = '.$this->mall['id'])
                    ->where($where)
                    ->group('a.id')
                    ->having($having)
                    ->field('a.id as store_id,a.user_id,a.name as store_name,c.name as category_name,a.logo,count(b.id) as goods_count,if(d.id > 0,"1","2") as status')
                    ->select();
        $this->assign('list',$list);

sql原句如下:

SELECT a.id as store_id,a.user_id,a.name as store_name,c.name as category_name,a.logo,count(b.id) as goods_count,if(d.id > 0,"1","2") as status FROM sh_store a LEFT JOIN sh_goods b on a.id = b.store_id LEFT JOIN sh_category c on a.category_id = c.id LEFT JOIN sh_mall_shop d on a.id = d.store_id and d.mall_id = 9 WHERE ( a.category_id = '47' ) AND ( (a.user_id in ( SELECT `id` FROM `sh_user` WHERE ( `agent_id` = 13 ) AND ( `status` = 1 ) )) ) AND ( a.status = 1 ) GROUP BY a.id HAVING status =1 

 

转载于:https://www.cnblogs.com/jiqing9006/p/5085216.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值