mysql - CakePHP LEFT JOIN 在有条件的多个表上

标签 mysql cakephp left-join

我想使用这个 CakePHP 表单进行左连接。参见 CakePHP Book - section on Joining Tables

$options['joins'] = array(
    array('table' => 'channels',
        'alias' => 'Channel',
        'type' => 'LEFT',
        'conditions' => array(
            'Channel.id = Item.channel_id',
        )
    )
);
$Item->find('all', $options);

除了我的 LEFT JOIN 有一个带条件的从属表。在 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

我可以使用 $options['joins'] 语法在 CakePHP 2.0 中做同样的事情吗?

最佳答案

所以经过一些摆弄之后,我发现这在 CakePHP 中起到了“诡计”。根据 SQL EXPLAIN,这比使用子查询在 LEFT 连接表上强制条件要快得多

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

关于mysql - CakePHP LEFT JOIN 在有条件的多个表上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18116290/

相关文章:

php - JSON.解析 : unexpected end of data at line 1 column 1 of the JSON data( Angular2 backend php server SQL)

email - 使用 Google 的 SMTP 服务器发送电子邮件

cakephp - 为什么 CakePHP 使用不同的复数/单数命名约定?

php - CakePHP 数据库连接 "Mysql"丢失,或无法创建

file - Cakephp 2.3.x发送文件并强制下载mp4文件

mysql - 获取最后一次对话

mysql - 如何使用 JOINED 表和 ORDER BY 和 OFFSET 改进 MySQL 查询

java - 登录表单 java mysql 在 netbeans 上失败

mysql - sql 在 LEFT JOIN 中使用一个 count() 另一个 count()

java - 如何在 Ebean 中对两个参数进行左连接?