表格是:
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
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/