【问题标题】:CakePHP, NOT IN or excluding JOIN?CakePHP,不加入或排除加入?
【发布时间】:2014-08-03 17:03:00
【问题描述】:

这些表格是:

units (id,...)   // approx' 10,000 units
contracts(id, unit_id, active, ...) // approx 50,000 records

我想获得所有没有附加合同的单位(和contracts.active=true)。

我的想法是: 使用NOT IN: 从单位中选择 * where id NOT IN(从contracts.active = true的合约中选择unit_id) 或者:

select * from units u
left join contracts c
on c.unit_id = u.id
where c.unit_id is null

而且,如果有在蛋糕中做的本地方法,请告诉我灯:)

谢谢

【问题讨论】:

    标签: mysql join cakephp-1.3


    【解决方案1】:

    根据您的其他联接是什么,NOT IN 可能会给您带来糟糕的性能。我建议使用以下 SQL 查询:

    SELECT * FROM units AS u
    LEFT JOIN contracts AS c
    ON (c.unit_id = u.id AND c.active = 1)
    WHERE c.id IS NULL
    

    根据cakephp documentation

    Cake 还可以检查空字段。在本例中,查询将返回帖子标题不为空的记录:

    array ("NOT" => array (
            "Post.title" => null
        )
    )
    

    因此,根据您的模型设置方式,这可能适合您:

    $joins = array(('table' => 'contracts',
                    'alias' => 'Contracts',
                    'type' => 'LEFT',
                    'conditions' => array('Contracts.active' => 0)));
    $conditions = array('Contracts.id' => NULL);
    $units = $this->Units->find('all', array('joins' => $joins, 'conditions' => $conditions));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-06
      • 2011-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多