MySQL内部查询与cakephp中的Where和Group by条件

标签 mysql cakephp

我有一个名为“Reports”的表,其中包含

 id report_id user_id 
  1     1       5
  2     1       5
  3     1       5
  4     2       5
  5     2       5
  6     3       6
  7     3       6
  8     4       1
  9     4       1
 10     4       1     

我正在尝试编写一个查询,使得 user_id = 5 并查找他创建了多少个报告。(答案应该是 2 )

我写了一个 Mysql 查询

  select count(distinct report_id) from Reports where user_id=5

我正在 Foreach 用户循环中尝试相同的 MYSQl 子查询,其中我的 5 来自 $user['User']['id'];

如何在 cakephp 框架的 for 循环中编写上面的 MYSQL 查询....

          foreach($users as & $user):

                echo "User id ".$user['User']['id'];

            $user['User']['report_count'] = $this->Report->find('count',
            array('conditions'=>array('Report.user_id'=>$user['User']['id'])));


        endforeach;

         $this->set('users', $users);

请建议我......如何在cakephp中编写上述Mysql查询

最佳答案

您想使用以下功能GROUP BYCOUNT

您的查询可能看起来像这样

select count(distinct report_id) from Reports where user_id=5

关于MySQL内部查询与cakephp中的Where和Group by条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1553543/

相关文章:

mysql - Hibernate 5.0.12找不到MySQL列

php - 禁用Cakephp的自动模型 "feature"

cakephp - 我如何使用find语句中的 'list'连接first_name和last_name两个不同的数据库字段来分配给cakephp中的下拉列表

PHP "Undefined Function"即使它实际上在同一个文件中

mysql - 在 mySQL 中的给定结果下方的表中选择最接近的数字

mysql - SQlite 多表引用

php 下拉选择仅插入表中的第一个单词

php - 想要将图像路径存储到 MySQL 时遇到麻烦

cakephp - 当字段为日期时间时,如何按日期查找项目?

angularjs - CORS - CakePHP 不接受 AngularJS JSON 请求