How to create a join that uses a subquery?

牧云@^-^@ 提交于 2019-12-08 05:27:02

问题


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


来源:https://stackoverflow.com/questions/49168867/how-to-create-a-join-that-uses-a-subquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!