我有三个表(这里简化):
recipients: recipientId, isGroup
users: userId, first name, last name
groups: groupid, groupname
如果收件人是用户,我想检索名字/姓氏,如果收件人是一个组,我想检索组名。收件人可能两者都不是(即已删除/不再存在的组),因此在这种情况下,我不想返回任何内容。
所以这就是我所做的:
select u.first_name, u.last_name, g.groupname, r.isGroup
from recipients r
left join users u on u.userid = r.recipientId
left join groups g on g.groupid = r.recipientId
where r.isGroup IS NULL or g.groupname IS NOT NULL
上述查询未返回预期结果。我得到了这个:
adam, smith, null, null
yolanda, smith, null, null
null, null, members, 1
null, null, null, 1
最后一行是出乎意料的,因为显然没有组名(g.groupname 为 NULL)并且 r.IsGroup = 1。
当我这样做时:
select u.first_name, u.last_name, g.groupname, r.isGroup
from recipients r
left join users u on u.userid = r.recipientId
left join groups g on g.groupid = r.recipientId
where r.isGroup IS NULL
我得到预期的结果:
adam, smith, null, null
yolanda, smith, null, null
当我这样做时:
select u.first_name, u.last_name, g.groupname, r.isGroup
from recipients r
left join users u on u.userid = r.recipientId
left join groups g on g.groupid = r.recipientId
where g.groupname IS NOT NULL
我得到预期的结果:
null, null, members, 1
只有当我将两个 where 子句与 OR 结合时,我才能获得额外的行。
现在,当我将查询更改为(从 IS NULL 更改为 ISNULL)时:
select u.first_name, u.last_name, g.groupname, r.isGroup
from recipients r
left join users u on u.userid = r.recipientId
left join groups g on g.groupid = r.recipientId
where r.isGroup IS NULL or ISNULL(g.groupname, null) IS NOT NULL
我得到了预期的结果:
adam, smith, null, null
yolanda, smith, null, null
null, null, members, 1
事实上,我什至不必更改 where 子句,以下查询也同样有效,并为我提供了如上所示的预期结果:
select u.first_name, u.last_name, ISNULL(g.groupname,null), r.isGroup
from recipients r
left join users u on u.userid = r.recipientId
left join groups g on g.groupid = r.recipientId
where r.isGroup IS NULL or g.groupname IS NOT NULL
所以,问题是,为什么?为什么将 ISNULL 放在我的 SELECT 语句中会改变 WHERE 子句的工作方式?为什么它会有所作为?为什么我的第一个查询不起作用?为什么只有当我添加 OR 时它才会起作用 - 为什么没有它它也不会损坏?
提前致谢。
我正在使用 MS SQL Server 2008。
编辑:修正错字,澄清问题