如何将以下SQL查询转换为CakePhp查询查询?
SELECT
a.id, a.rev, a.contents
FROM
YourTable a
INNER JOIN (
SELECT
id, MAX(rev) rev
FROM
YourTable
GROUP BY
id
) b ON a.id = b.id AND a.rev = b.rev
我尝试过以下代码:
return $model->find('all', [
'fields' => $fields,
'joins' => [
[
'table' => $model->useTable,
'fields' => ['id','MAX(rev) as rev'],
'alias' => 'max_rev_table',
'type' => 'INNER',
'group' => ['id'],
'conditions' => [
$model->name.'.id= max_rev_table.id',
$model->name.'.rev = max_rev_table.rev'
]
]
],
'conditions' => [
$model->name.'.emp_id' => $empId
]
]);
但似乎在生成的SQL中,joins
下的字段不包括在内。因此,我无法获得max(rev)
所需的max(rev)
只能获得joins
的行。
我已尝试重新排列SELECT company_code,
sum(case when st = 'FOR APPROVAL' then 1 else 0 end) FOR_APPROVAL,
sum(case when st = 'FOR AUTHORIZATION' then 1 else 0 end) FOR_AUTHORIZATION
FROM table
GROUP BY company_code
内的项目,但仍会生成相同的自动生成的SQL。
你能帮帮我吗?
答案 0 :(得分:5)
联接没有fields
或group
选项,唯一的选项是table
,alias
,type
和conditions
。
如果要加入子查询,则需要显式生成一个:
$ds = $model->getDataSource();
$subquery = $ds->buildStatement(
array(
'fields' => array('MaxRev.id', 'MAX(rev) as rev'),
'table' => $ds->fullTableName($model),
'alias' => 'MaxRev',
'group' => array('MaxRev.id')
),
$model
);
并将其传递给联接table
选项:
'table' => "($subquery)"
另见