Cakephp 3:如何使用Cakephp的Query Builder在内连接中进行聚合select语句?

时间:2017-07-04 16:18:00

标签: cakephp cakephp-3.x cakephp-3.4

好吧,我似乎无法弄清楚这一点。我正处于解决这个问题的第二天,是时候争取一些帮助了。

这是有效的SQL:

SELECT rt1.request_id, rt1.status 
FROM request_transactions rt1 
INNER JOIN (
    SELECT max(id) AS max_id 
    FROM request_transactions 
    GROUP BY request_id
) AS rt2 ON rt1.id = rt2.max_id;

我是如何使用Cakephp 3查询构建器编写的?对于具有聚合函数(max)的内连接,我完全陷入困境。

非常感谢提前。

编辑:这是表格列和数据,如果有帮助:

SELECT id, user_id, created, modified FROM requests;

 id | user_id |       created       |      modified       
----+---------+---------------------+---------------------
 94 |     101 | 2017-07-04 18:20:47 | 2017-07-04 18:21:26
 95 |     101 | 2017-07-04 18:48:14 | 2017-07-04 18:48:14
 96 |     101 | 2017-07-04 18:48:40 | 2017-07-04 18:48:40
(3 rows)

SELECT id, status, created, request_id FROM request_transactions;                    

 id  |  status  |       created       | request_id 
-----+----------+---------------------+------------
 127 | created  | 2017-07-04 18:20:47 |         94
 128 | read     | 2017-07-04 18:21:03 |         94
 129 | rejected | 2017-07-04 18:21:26 |         94
 130 | created  | 2017-07-04 18:48:14 |         95
 131 | created  | 2017-07-04 18:48:40 |         96
(5 rows)

SELECT rt1.request_id, rt1.status 
FROM request_transactions rt1 
INNER JOIN (
    SELECT max(id) AS max_id 
    FROM request_transactions 
    GROUP BY request_id
) AS rt2 ON rt1.id = rt2.max_id;

 request_id |  status  
------------+----------
         96 | created
         94 | rejected
         95 | created
(3 rows)

2 个答案:

答案 0 :(得分:1)

好的!经过一番混乱之后,我想我已经拥有了它:

$requestTransactionsModel = $this->loadModel('RequestTransactions');

$query = $requestTransactionsModel->find('all');
$query->select([
    'max_id' => $query->func()->max('id'),
])
->group('request_id');

$query2 = $requestTransactionsModel->find('all');
$query2->select([
    'request_id',
    'status',
])
->join([
    'table' => $query,
    'alias' => 'rt2',
    'type' => 'INNER',
    'conditions' => ['rt2.max_id = RequestTransactions.id'],
]);

这提供了与问题中发布的SQL相同的数据。我有两个部分很难找到答案:

我不知道你可以在join()中使用查询作为表名。这是反复试验。

我希望条件采用格式

conditions => ['rt2.max_id' => 'RequestTransactions.id']

那不行。它在RequestTransactions.id周围加上引号。它需要写成

conditions => ['rt2.max_id = RequestTransactions.id']

答案 1 :(得分:0)

你可以试试这个:

$result = $this->$requestTransactionsModel->find('all')->join(
    ['requests'=>[
      'table'=>'requests',
      'alias'=>'r',
      'type'=>'inner',
      'conditions'=>['request_transactions.id = r.max_id'],
      ])->group('request_transactions.request_id');