Mysql CakePHP在具有条件的多个表上左联接
我想用这个CakePHP表单做一个左连接。看 除了我的左连接有一个带条件的依赖表。在MySQL中,连接如下所示Mysql CakePHP在具有条件的多个表上左联接,mysql,cakephp,left-join,Mysql,Cakephp,Left Join,我想用这个CakePHP表单做一个左连接。看 除了我的左连接有一个带条件的依赖表。在MySQL中,连接如下所示 LEFT JOIN ( channels as Channel INNER JOIN regions as Region ON ( Region.id = Channel.region_id and Region.id=1 ) ) ON Channel.id = Item.channel_id 在CakePHP 2.0中,我可以使用$options['joi
LEFT JOIN (
channels as Channel
INNER JOIN regions as Region ON ( Region.id = Channel.region_id and Region.id=1 )
) ON Channel.id = Item.channel_id
在CakePHP 2.0中,我可以使用
$options['joins']
语法做同样的事情吗?所以经过一点修改,我发现这在CakePHP中起到了“作用”。根据SQLExplain,这是一种比使用子查询强制左侧联接表上的条件快得多的联接
$options['joins'] = array(
array('table' => '(channels as `Channel` INNER JOIN regions as `Region`
ON ( `Region`.id = `Channel`.region_id and `Region`.id=1 ))',
// 'alias' => 'Channel', // the alias is 'included' in the 'table' field
'type' => 'LEFT',
'conditions' => array(
'Channel.id = Item.channel_id',
)
)
);
$Item->find('all', $options);
所以经过一点修改,我发现这在CakePHP中起到了“作用”。根据SQLExplain,这是一种比使用子查询强制左侧联接表上的条件快得多的联接
$options['joins'] = array(
array('table' => '(channels as `Channel` INNER JOIN regions as `Region`
ON ( `Region`.id = `Channel`.region_id and `Region`.id=1 ))',
// 'alias' => 'Channel', // the alias is 'included' in the 'table' field
'type' => 'LEFT',
'conditions' => array(
'Channel.id = Item.channel_id',
)
)
);
$Item->find('all', $options);
连接选项中的条件键也可以工作
连接中的条件键选项可能太晚了一点,但是对于那些像我一样通过谷歌看到这一点的人,你应该尝试以下方法
$options['joins'] = array(
array(
'table' => 'channels',
'alias' => 'Channel',
'type' => 'LEFT',
'conditions' => array(
'Item.channel_id = Channel.id'
)
),
array(
'table' => 'regions',
'alias' => 'Region',
'type' => 'INNER',
'conditions' => array(
'Channel.region_id = Region.id',
'Region.id = 1'
)
)
);
有点晚了,但是对于那些像我一样通过谷歌看到这一点的人来说,你应该试试下面的方法
$options['joins'] = array(
array(
'table' => 'channels',
'alias' => 'Channel',
'type' => 'LEFT',
'conditions' => array(
'Item.channel_id = Channel.id'
)
),
array(
'table' => 'regions',
'alias' => 'Region',
'type' => 'INNER',
'conditions' => array(
'Channel.region_id = Region.id',
'Region.id = 1'
)
)
);
不,那是错的。您仍然需要将区域表添加到联接中,如果单独添加,则必须为其指定单独的左/内联接类型。你会得到不同的结果。您可以将区域和通道一起添加到子选择中,但这是一个慢得多的查询。并且包含()和模型关联?在条件数组中有一个单引号的遗漏位置。应该有'Region.id=1'****而不是'Region.id'=1不,这是错误的。您仍然需要将区域表添加到联接中,如果单独添加,则必须为其指定单独的左/内联接类型。你会得到不同的结果。您可以将区域和通道一起添加到子选择中,但这是一个慢得多的查询。并且包含()和模型关联?在条件数组中有一个单引号的遗漏位置。应该有“Region.id=1”****而不是“Region.id=1”