sql - WHERE 子句中的 IS NOT NULL 和 ISNULL(str, NULL)

标签 sql sql-server isnull

我有三个表(这里简化):

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

所以,问题是,为什么? 为什么在我的 SELECT 语句中放入 ISNULL 会改变 WHERE 子句的工作方式? 为什么它会有所不同? 为什么我的第一个查询不起作用?为什么只有当我添加 OR 时它才会起作用 - 为什么没有它它也不会损坏?

提前致谢。

我使用的是 MS SQL Server 2008。

编辑:修正错字,澄清问题

最佳答案

我们发现这是未安装服务包的 Sql Server 2008 中的问题。尝试安装 SP1 或 SP2。在我们的例子中,Service Pack 解决了这个问题。

关于sql - WHERE 子句中的 IS NOT NULL 和 ISNULL(str, NULL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7421835/

相关文章:

sql - 如何加快这个查询?

mysql - SELECT 将检查超过 MAX_JOIN_SIZE 行

c# - MVC4从SQL Server表检索图像文件到html图像

mysql 如果不为空,则为 0 或 ""

c# - 用默认文本替换空值

sql - CREATE OR ALTER PROCEDURE 中关键字 'OR' 附近的语法不正确

python - 改进 SQL INSERT 查询以避免 sql 注入(inject)

sql-server - 将 ApplicationIntent=ReadOnly 与将数据插入临时表的存储过程一起使用

c# - 如何为 session 切换到 SQL 服务器状态....我收到一个错误

android - 抛出空异常的 HTTP 请求