==寻找效率最高的sql语句:在结构相同的两表中找出不同的记录(Sql Server 2000)==

ChinaOneCup 2013-08-12 10:25:05
例如:
表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)
上面那条语句效率高,或者是否还有别的更高效率语句
...全文
142 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
KeepSayingNo 2013-08-13
  • 打赏
  • 举报
回复
都是求差集操作,没有啥区别,这两种写法都可以
dyf0130 2013-08-13
  • 打赏
  • 举报
回复
引用 3 楼 wwwwgou 的回复:
[quote=引用 2 楼 hdhai9451 的回复:] 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)
SELECT * 和SELECT 1在EXISTS用法中,应该不存在效率的问题。[/quote] 在语法分析上,应该还是有区别的吧
Shawn 2013-08-13
  • 打赏
  • 举报
回复
引用 2 楼 hdhai9451 的回复:
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)
SELECT * 和SELECT 1在EXISTS用法中,应该不存在效率的问题。
mylife21 2013-08-13
  • 打赏
  • 举报
回复
为啥不考虑用except
Andy__Huang 2013-08-12
  • 打赏
  • 举报
回复
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)
Shawn 2013-08-12
  • 打赏
  • 举报
回复
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

34,587

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧