【问题标题】:How to order by aggregate function results?如何按聚合函数结果排序?
【发布时间】:2017-12-02 04:41:23
【问题描述】:

如何得到下表的结果。

catTbl

catId, name
11     fruit
12     vegetable

prodTbl

pId | catTbl_catId | name
1     11             apple
2     11             orange
3     12             slag

我想得到结果

 cat name     total count
 fruit        2
 vegetable    1

按总数排序--

如何在 cakephp 3 查询下使用按总计排序..

 $cats=$this->catTbl->find()
            ->where(['catTbl.status'=>'1','is_deleted'=>'0'])
            ->select(['name','catId','modified'])          
            ->contain([
            'prodTbl' => function($q) {
              $q->select([
                   'prodTbl.catTbl_catId',
                   'total' => $q->func()->count('prodTbl.catTbl_catId')
              ])
              ->where(['prodTbl.status'=>'1','prodTbl.is_deleted'=>'0'])
              ->group(['prodTbl.catTbl_catId']);

              return $q;
          }
          ]);

【问题讨论】:

    标签: cakephp sql-order-by aggregate-functions query-builder cakephp-3.4


    【解决方案1】:

    我设法得到了结果

    +------------+---------+
    |    Cat     |  Total  |
    +------------+---------+
    | fruit      |    2    |
    | vegetable  |    1    |
    +------------+---------+
    

    使用这个查询

    $query = $this->Prod->find();
    
        $cats = $query->select([
            'Cat.name',
            'total' => $query->func()->count('catId')
        ])
        ->contain([
            'Cat'
        ])
        ->group([
            'catId'
        ])
        ->order([
            'total' => 'DESC'
        ])
        ->all();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-24
      • 1970-01-01
      • 2019-04-02
      • 1970-01-01
      • 2020-03-17
      • 1970-01-01
      • 2015-02-15
      相关资源
      最近更新 更多