如何创建使用子查询的联接? [英] How to create a join that uses a subquery?
问题描述
如何将以下SQL查询转换为CakePhp查找查询?
How do you convert the following SQL Query to a CakePhp Find Query?
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)
的行.
But it seems that in the generated SQL, the fields under the joins
is not included. So I don't get the max(rev)
which I need to get only the rows with max(rev)
.
我尝试重新排列joins
中的项目,但仍会生成相同的自动生成的SQL.
I have tried rearranging the items inside joins
but still produces same auto-generated SQL.
你能帮我吗?
推荐答案
没有用于联接的fields
或group
选项,唯一的选项是table
,alias
,type
和
There are no fields
or group
options for joins, the only options are table
, alias
, type
, and conditions
.
如果要加入子查询,则需要显式生成一个子查询:
If you want to join a subquery, then you need to explicitly generate one:
$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
选项:
and pass it to the joins table
option:
'table' => "($subquery)"
另请参见
这篇关于如何创建使用子查询的联接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!