http://www.jb51.net/article/23293.htm
但是用IN的sql性能总是比较低的,从sql执行的步骤来分析用IN的sql与不用IN的sql有以下区别:
sql试图将其转换成多个表的连接,如果转换不成功则先执行IN里面的子查询,再查询外层的表记录,如果转换成功则直接采用多个表的连接方式查询。由此可见用IN的sql至少多了一个转换的过程。一般的sql都可以转换成功,但对于含有分组统计等方面的sql就不能转换了。 推荐在业务密集的sql当中尽量不采用IN操作符NOT IN 此操作是强列推荐不使用的,因为它不能应用表的索引。推荐用NOT EXISTS 或(外连接+判断为空)方案代替
在数据库中有两个表,一个是当前表Info(id,PName,remark,impdate,upstate),一个是备份数据表bakInfo(id,upstate),将当前表数据备份到备份表去,就涉及到not in 和in 操作了:
首先,添加10万条测试数据
create procedure AddData
as
declare @id int
set @id=0
while(@id<100000)
begin
insert into dbo.Info(id,upstate)
values(@id,convert(varchar,@id)+'0','abc',getdate(),0)
set @id=@id+1
end
exec AddData
使用not in 和in操作:
复制代码代码如下:
SET STATISTICS TIME ON
GO
--备份数据
insert into bakInfo(id,upstate)
select id,upstate from dbo.Info
where id not in(select id from dbo.bakInfo)
GO
SET STATISTICS TIME OFF
此操作执行时间:
复制代码代码如下: