在cakephp中使用Where和Group by条件进行MySQL内部查询

问题描述 投票:0回答:3

我有一个名为“报告”的表,其中

 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查询

php mysql cakephp
3个回答
2
投票

您想使用以下函数 GROUP BYCOUNT

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

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

1
投票

如果这是您在应用程序中显示的用户列表...您可以显着减少正在运行的查询数量。 例如。对于 100 个用户,您将运行 100 个查询,而不是您可以运行单个查询来提取 user_id 和每个用户的报告计数

select count(distinct report_id) as count,user_id from Reports where user_id IN (1,2) GROUP BY user_id;

或者如果您想为每个用户运行单独的查询

select count(distinct report_id) as count,user_id from Report where user_id=5;

0
投票

试试这个:

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

它应该获取给定

report_id
的所有不同的
user_id
,然后对它们进行计数。基本上,它应该运行查询:

SELECT DISTINCT report_id FROM Reports WHERE user_id=$user['User']['id']

(代入

$user['User']['id']
的值后),然后统计结果的行数。警告:我在现实生活中不使用 CakePHP,我只是阅读了文档;你的旅费可能会改变。正如 halocursed 提到的,自行运行单个 SQL query 比为每个用户 ID 调用
find(...)
更有效。您也可以尝试:

$report_counts = $this->Report->find('list',
    array( 'conditions' => array('Report.user_id' => array_map(create_function('$user', 'return $user["User"]["id"];'), $users)),
        'group'  => array('Report.user_id'),
        'fields' => array('Report.user_id', 'COUNT(DISTINCT Report.report_id) AS report_count')
    )
);
foreach ($users as &$user) {
    $user['User']['report_count'] = $report_counts[$user['User']['id']];
}

但是,我不知道 CakePHP 是否会接受

'fields'
参数中的聚合函数,并且我不知道
find('list', ...)
是否会选择
Report.user_id
作为数组索引。如果您对后者有问题,可以切换到
[find('all', ...)][3]
调用并循环
$report_counts
而不是
$users
。我没有采用这种方法,因为我不知道 $users 的结构,例如它是如何索引的。

© www.soinside.com 2019 - 2024. All rights reserved.