【问题标题】:Subqueries in Cakephp 3.0Cakephp 3.0 中的子查询
【发布时间】:2016-11-11 07:35:51
【问题描述】:

如何转换 Mysql 查询:

SELECT * , (

SELECT COUNT( * ) 
FROM articles
WHERE  `user_id` =1
) AS total_count
FROM articles
WHERE  `user_id` =1
GROUP BY user_id

进入 cakephp 子查询?

我试过了,

$articlescount = $this->Articles->find('all')->where(['user_id' => 1])->count();
print_r($articlescount);

这只会返回我的数量。

【问题讨论】:

    标签: sql cakephp-3.0


    【解决方案1】:

    我怀疑您正在使用的查询是实现您想要实现的目标的最佳方式,因为查询和子查询似乎返回相同的值

    无论如何,这就是您获得与您询问的完全相同的查询的方式

    $q = $this->Articles->find();
    
    $q->select([$q->func()->count('*')])
        ->where(['user_id' => 1]);
    
    $q2 = $this->Users->find()
        ->select(['total_count' => $q])
        ->autoFields(true)
        ->where(['user_id' => 1])
        ->group(['user_id'])
        ->all();
    

    $q 是子查询,而$q2 是您想要的实际查询。

    顺便说一句,我认为你可以简单地做

    $q = $this->Users->find()
        ->select(['total_count' => $q->func()->count('*')])
        ->autoFields(true)
        ->where(['user_id' => 1])
        ->group(['user_id']);
    

    【讨论】:

      【解决方案2】:

      Ariala 的评论几乎不错,但我认为这段代码更灵活,因为 suquery 不包含用户 ID 固定条件:

      $q = $this->Articles->find();
      
      $q->select([$q->func()->count('*')])
            ->where(['Articles.user_id = Users.id']);
      
      $q2 = $this->Users->find()
               ->select(['id',  'first_name',  'total_count' => $q])
               ->where(['id' => 1])
               ->all();
      

      但是,如果您想列出所有具有文章计数的用户,您可以在 $q2 中保留 where 条件。

      结果如下:

      id | first_name | total_count
      1  | John       | 3
      2  | Doe        | 0
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多