OK I must be missing something really simple here. I just want to return all records from a table where the user_id matches (easy!) and the 'paid' field is either NULL or 0. My 'paid' field is a TinyInt (1).
My CakePHP model code is:
$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
)
));
The SQL generated by CakePHP is like this:
SELECT `Subscription`.`id`, `Subscription`.`paid` FROM `subscriptions` AS `Subscription` WHERE `Subscription`.`user_id` = 3 AND NOT (`Subscription`.`paid` = '1') LIMIT 1
Common sense would say this should work. The problem is that that SQL will return rows containing 0 in the 'paid' column, but will never return NULLs.
Is there any way to return zero's and NULLs in the one stroke, without using 'or'?
Thanks in advance.
A NULL boolean has three possible values: true , false , and null . A NOT NULL boolean has only two, true and false . Your application logic will have to suffice for telling you which is the correct choice.
BOOLEAN can have TRUE or FALSE values. BOOLEAN can also have an “unknown” value, which is represented by NULL. Boolean columns can be used in expressions (e.g. SELECT list), as well as predicates (e.g. WHERE clause).
To test for NULL in a query, you use the IS NULL or IS NOT NULL operator in the WHERE clause. You can use the IS NOT operator to get all leads who provided the email addresses. Even though the NULL is not equal to NULL , two NULL values are equal in the GROUP BY clause.
Let's look at an example of how to use MySQL IS NULL in a SELECT statement: SELECT * FROM contacts WHERE last_name IS NULL; This MySQL IS NULL example will return all records from the contacts table where the last_name contains a NULL value.
When you left join a table with a boolean field, the result set may contain a NULL value even though the joined table's schema does not permit it.
So as a general case I would suggest:
where `Subscription`.`paid` = 0 or `Subscription`.`paid` IS NULL
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With