Im trying to get all available keys, meaning keys which have been returned (return_date is not null), key hasn’t been lost (lost_key = false), and keys never been rented before (id is null). However when I run this I get 0 recirds. If I remove the id condition, I only get keys which have been rented before and all the keys which are not in the keyActivity table are ignored. Does anyone know what I am doing wrong?
SELECT a.key_id, a.drawer_num
FROM
keys AS a
left outer JOIN keyActivity AS b
ON a.key_id = b.key_id
WHERE
return_date is not null
and lost_key =false
and id is null;

SOLUTION USED:
SELECT a.key_id, a.drawer_num
FROM keys AS a LEFT JOIN keyActivity AS b ON a.key_id = b.key_id
WHERE (b.return_date is not null
and b.lost_key =false)
OR b.id is null;
idmay be a field in both tables, and if this is so, your conditionid is nullwill be interpreted erroneously as theidofkeysto beNULL, thus resulting in an empty result set.It should work if you call it by its full name, i.e.
b.idbecause you want to exclude any previouskeyActivity.However, I also believe you want to have both previous conditions connected by
ANDand in parentheses, and then the last condition connected byORbecause previous key activity is okay as long as the key has been returned.EDIT: I rearranged the conditions, to also catch the case in which the clerk loses a key before ever handing it out.