我刚刚在WHERE子句中遇到过这个问题:
AND NOT (t.id = @id)
与此相比如何:
AND t.id != @id
或者用:
AND t.id <> @id
我总是自己写下后者,但显然别人有不同的想法。一个人的表现会比另一个好吗?我知道使用<>
或!=
会破坏使用我可能拥有的索引的任何希望,但肯定上面的第一种方法会遇到同样的问题吗?
答案 0 :(得分:42)
这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&lt;&gt; @id我自己
答案 1 :(得分:31)
请注意,!=运算符不是标准SQL。如果您希望您的代码可移植(即,如果您关心),请使用&lt;&gt;代替。
答案 2 :(得分:9)
只是稍微调整一下后来的人:
等值运算符在存在空值时生成未知值 并且未知值被视为假。 不(未知)未知
在下面的例子中,我将试着说一对(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
请注意,我们希望得到结果:
但我们得到另一个结果
答案 3 :(得分:5)
没有任何表现,两种说法完全相同。
HTH