我刚刚在 WHERE 子句中遇到了这个:

AND NOT (t.id = @id)

这与以下内容相比如何:

AND t.id != @id

或者与:

AND t.id <> @id

我总是自己写后者,但显然其他人有不同的想法。其中一个的表现会比另一个更好吗?我知道使用 <> 或者 != 将会破灭我可能拥有的使用索引的任何希望,但是 一定 上面的第一种方法会遇到同样的问题吗?

有帮助吗?

解决方案

这 3 个将得到完全相同的执行计划

declare @id varchar(40)
select @id = '172-32-1176'

select * from authors
where au_id <> @id

select * from authors
where au_id != @id

select * from authors
where not (au_id = @id)

当然,这还取决于索引本身的选择性。我自己总是使用 au_id <> @id

其他提示

请注意,!= 运算符不是标准 SQL。如果您希望代码可移植(也就是说,如果您关心),请改用 <>。

对于后来的人来说,稍微调整一下:

当有空时,平等运算符会产生一个不知道的值,并且未知值被处理为假。不(未知)未知

在下面的示例中,我将尝试判断一对 (a1, b1) 是否等于 (a2, b2)。请注意,每列都有 3 个值 0、1 和 NULL。

DECLARE @t table (a1 bit, a2 bit, b1 bit, b2 bit)

Insert into @t (a1 , a2, b1, b2) 
values( 0 , 0 , 0 , NULL )

select 
a1,a2,b1,b2,
case when (
    (a1=a2 or (a1 is null and a2 is null))
and (b1=b2 or (b1 is null and b2 is null))
)
then 
'Equal'
end,
case when not (
    (a1=a2 or (a1 is null and a2 is null))
and (b1=b2 or (b1 is null and b2 is null))
)
then 
'not Equal'
end,
case when (
    (a1<>a2 or (a1 is null and a2 is not null) or (a1 is not null and a2 is null))
or (b1<>b2 or (b1 is null and b2 is not null) or (b1 is not null and b2 is null))
)
then 
'Different'
end
from @t

请注意,这里我们期望结果:

  • 等于空
  • 不等于不相等
  • 因不同而不同

但我们得到另一个结果

  • 等于 null OK
  • 不等于为空???
  • 不同就是不同

不会对性能造成影响,两种说法完全相等。

华泰

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top