如何创建使用子查询的联接? [英] How to create a join that uses a subquery?

查看:157
本文介绍了如何创建使用子查询的联接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将以下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.

你能帮我吗?

推荐答案

没有用于联接的fieldsgroup选项,唯一的选项是tablealiastype.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆