日期:2014-05-17  浏览次数:20426 次

==寻找效率最高的sql语句:在结构相同的两表中找出不同的记录(Sql Server 2000)==
例如:
表1
  ID  电话号码    
  01   1111111
  02   2222222
  03   3333333
  04   3332222
表2
  ID  电话号码
  01   1111111
  02   2222222

结果: 将03,04 两条记录找出来(找出表1不同于表2的记录即可
select ID from 表1 where ID not in (select ID from 表2)
select ID from 表1 where not exist(select * from 表2 where 表1.ID=表2.ID)
上面那条语句效率高,或者是否还有别的更高效率语句

------解决方案--------------------
if OBJECT_ID('tempdb..#temp', 'u') is not null   drop table #temp;
CREATE TABLE #temp(ID INT, 电话号码 VARCHAR(20))
insert #temp
select '01','1111111' union all
select '02','2222222' union all
select '03','3333333' union all
select '04','3332222'
CREATE TABLE #temp2(ID INT, 电话号码 VARCHAR(20))
insert #temp2
select '01','1111111' union all
select '02','2222222'

select ID from #temp where ID not in (select ID from #temp2) --如果#temp2中存在NULL值,查询结果将为空
select ID from #temp a where not EXISTS (select * from #temp2 b where a.ID=b.ID)  --在ID字段有索引的情况下,效率比较高
SELECT a.id FROM #temp a LEFT JOIN #temp2 b ON a.ID = b.ID WHERE b.id IS NULL --虽然效果和NOT EXISTS相同,但效率不高

--楼主可Ctrl+L看一下它们3个的执行计划,虽然暂时看来开销都一样(33%),但随着数据库增大,建议先用NOT EXISTS

------解决方案--------------------
select ID from 表1 where not exist(select * from 表2 where 表1.ID=表2.ID)
这句效率高,但select * 改为常数select 1
select ID from 表1 where not exist(select 1 from 表2 where 表1.ID=表2.ID)

------解决方案--------------------