在T-SQL中测试不平等
时间:2020-03-05 18:38:58 来源:igfitidea点击:
我刚刚在WHERE子句中遇到了这个问题:
AND NOT (t.id = @id)
与以下内容相比如何:
AND t.id != @id
或者搭配:
AND t.id <> @id
我总是会自己写后者,但显然其他人的看法有所不同。一个人的表现会比另一个人好吗?我知道使用<>
或者!=
会让使用我可能拥有的索引的希望破灭,但是上述第一种方法肯定会遇到同样的问题吗?
解决方案
回答
这不会对性能造成任何影响,两个语句完全相等。
高温超导
回答
请注意,!=运算符不是标准SQL。如果我们希望代码具有可移植性(也就是说,如果我们愿意),请使用<>代替。
回答
这三个将获得相同的确切执行计划
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
回答
稍稍调整一下以后再来的人:
当存在空值时,等于运算符将生成未知值
并将未知值视为错误。
不(未知)未知
在下面的示例中,我将尝试说一对(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
请注意,在这里我们期望得到结果:
- 等于空
- 不等于不等于
- 与众不同
但是我们得到另一个结果
- 等于为空OK
- 不等于为空???
- 不同就是不同