mysql - CakePHP,不加入或排除加入?

标签 mysql join cakephp-1.3

表格是:

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

我想获取所有没有附加契约(Contract)的单位(以及contracts.active=true)。

我的想法是: 使用NOT IN: 从单位中选择* 其中 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

并且,如果有一种本地方法可以在蛋糕中做到这一点,请告诉我:)

谢谢

最佳答案

根据您的其他连接,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 can also check for null fields. In this example, the query will return records where the post title is not null:

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

关于mysql - CakePHP,不加入或排除加入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25106987/

相关文章:

mysql - 获取两个表的唯一行

Mysql count、join、dual结合使用

mysql - CakePHP 1.3.x 找到 ('count' ) 与 'contains' , 'group' , 'order' 和 'limit' SQL 等效语句

SQL Server 在列上合并联接后选择

php - 使用 PHP7 的 Cakephp

php - 转换mysql中的日期

php - 获取除 first() 以外的特定行

java - MySQL/Java : Incorrect date value: '1990' for column

php - 以正确的方式输出数组

sql - mysql 有条件连接