WHERE子句将非空字段与null进行比较

时间:2013-06-05 18:06:10

标签: sql

我的sql语句面临着一个奇怪的问题。也许这是愚蠢的事情,我无法抓住它。

SELECT appointment.patient_id,
       patient.notes,
       patient.first_name,
       CONVERT(VARCHAR(27), appointment.start_time, 100),
       patient.email_address
FROM   appointment,
       patient
WHERE  Day(appointment.start_time) = 06
       AND Month(appointment.start_time) = 06
       AND Year(appointment.start_time) = 2013
       AND appointment.appointment_type_id != ''
       AND appointment.location_id != ''
       AND appointment.patient_id = patient.patient_id
       AND patient.email_address != ''; 

以上查询返回3条记录。 'notes'字段的值在所有3条记录中都是NULL。 如果我添加标准patient.notes != '1 Reminder',它不应该返回相同的结果集吗?当我尝试它时,它返回零记录。有人可以解释原因吗?

2 个答案:

答案 0 :(得分:2)

不,你的期望是错误的。除NULL之外,与IS NULL的任何比较都为NULL(视为false)。

因此,patient.notes != '1 Reminder'为false,正如patient.notes = '1 Reminder'为假。你可以这样做:

coalesce(patient.notes, '') != '1 Reminder'

答案 1 :(得分:1)

对于NULL值,A!=运算符不会解析为true。要获取除“1提醒”,包括 NULL之外的记录,请使用“patient.notes!='1 Reminder'或patient.notes IS NULL”。

相关问题