nin*_*ded 46 t-sql indexing inequality
我刚刚在WHERE子句中遇到过这个问题:
AND NOT (t.id = @id)
Run Code Online (Sandbox Code Playgroud)
这与以下方面相比如何:
AND t.id != @id
Run Code Online (Sandbox Code Playgroud)
或者:
AND t.id <> @id
Run Code Online (Sandbox Code Playgroud)
我总是自己写下后者,但显然别人有不同的想法.一个人的表现会比另一个好吗?我知道使用<>
或!=
将要破坏使用我可能拥有的索引的任何希望,但是上面的第一种方法肯定会遇到同样的问题吗?
SQL*_*ace 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)
Run Code Online (Sandbox Code Playgroud)
当然,它还取决于指数本身的选择性.我总是自己使用au_id <> @id
小智 9
只是稍微调整一下后来的人:
当存在null并且未知值被视为false时,等于运算符生成未知值.不(未知)未知
在下面的例子中,我将试着说一对(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
Run Code Online (Sandbox Code Playgroud)
请注意,这里我们期待结果:
但我们得到另一个结果