How to create a join that uses a subquery?

2019-05-29 12:35发布

问题:

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

I have tried the code below:

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
    ]
]);

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).

I have tried rearranging the items inside joins but still produces same auto-generated SQL.

Can you please help me?

回答1:

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
);

and pass it to the joins table option:

'table' => "($subquery)"

See also

  • Cookbook > Models > Associations: Linking Models Together > Joining tables
  • Cookbook > Models > Retrieving Your Data > Sub-queries