jos*_*ing 6 mysql cakephp cakephp-2.0 cakephp-2.1
好的,我一定在这里遗漏了一些非常简单的东西。我只想从 user_id 匹配的表中返回所有记录(简单!)并且“已支付”字段为 NULL 或 0。我的“已支付”字段是 TinyInt (1)。
我的 CakePHP 模型代码是:
$workingRecord = $this->find('first',array(
'conditions'=>array(
'Subscription.user_id'=>$userId,
array('not' => array('Subscription.paid' => true)) // Not True, to catch both false or NULL values
)
));
Run Code Online (Sandbox Code Playgroud)
CakePHP 生成的 SQL 是这样的:
SELECT `Subscription`.`id`, `Subscription`.`paid` FROM `subscriptions` AS `Subscription` WHERE `Subscription`.`user_id` = 3 AND NOT (`Subscription`.`paid` = '1') LIMIT 1
Run Code Online (Sandbox Code Playgroud)
常识会说这应该有效。问题是 SQL 将返回 'paid' 列中包含 0 的行,但永远不会返回 NULL。
有没有办法在不使用“或”的情况下一次性返回零和空值?
提前致谢。
当您使用布尔字段连接表时,即使连接表的架构不允许,结果集也可能包含 NULL 值。
因此,作为一般情况,我建议:
where `Subscription`.`paid` = 0 or `Subscription`.`paid` IS NULL
Run Code Online (Sandbox Code Playgroud)
如果您的字段是 TINYINT(1),则不应有任何 NULL 值。 如果这样做,请运行快速查询以将所有 NULL 替换为默认值,并将数据库字段设置为默认值 1 或 0。
那么,你的代码应该是:
$workingRecord = $this->find('first',array(
'conditions'=>array(
'Subscription.user_id'=>$userId,
'Subscription.paid' => 0
)
));
Run Code Online (Sandbox Code Playgroud)
它没有像您想象的那样工作的原因:
逻辑非。如果操作数为 0,则计算结果为 1;如果操作数非零,则计算结果为 0;NOT NULL 返回 NULL。
所以 - 在你的例子中,你说的"NOT 1"是 MySQL 翻译成的" = 0"。