not exists和not in

mayuanf 2012-06-03 10:20:05


set nocount on
create table a(id int);
create table b(id int);
go


insert into A values(RAND(checksum(newid()))*100);
go 1000

insert into B values(RAND(checksum(newid()))*100);
go 10

set showplan_text on
select * from b
where id not in (select id from a)

select * from b
where not exists(Select 1 from a where a.id = b.id)



--not in(cost 70%)
| |--Nested Loops(Left Anti Semi Join, WHERE:([master].[dbo].[b].[id] IS NULL))
| | |--Table Scan(OBJECT:([master].[dbo].[b]))
| | |--Top(TOP EXPRESSION:((1)))
| | |--Table Scan(OBJECT:([master].[dbo].[a]))
| |--Row Count Spool
| |--Table Scan(OBJECT:([master].[dbo].[a]), WHERE:([master].[dbo].[a].[id] IS NULL))
|--Top(TOP EXPRESSION:((1)))
|--Table Scan(OBJECT:([master].[dbo].[a]), WHERE:([master].[dbo].[b].[id]=[master].[dbo].[a].[id]))

-- not exists (cost 30%)
|--Nested Loops(Left Anti Semi Join, OUTER REFERENCES:([master].[dbo].[b].[id]))
|--Table Scan(OBJECT:([master].[dbo].[b]))
|--Top(TOP EXPRESSION:((1)))
|--Table Scan(OBJECT:([master].[dbo].[a]), WHERE:([master].[dbo].[a].[id]=[master].[dbo].[b].[id]))


为啥not exists会有这么蛋疼的执行计划呢。 我本来一直以为它们俩是一样的呢(除了对null的处理不同)。
...全文
121 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
以学习为目的 2012-06-04
  • 打赏
  • 举报
回复
相同数据量的话,这两种写法到底开销一样不?
q107770540 2012-06-04
  • 打赏
  • 举报
回复
路过,学习一下
叶子 2012-06-03
  • 打赏
  • 举报
回复
select * from b except select * from a
mayuanf 2012-06-03
  • 打赏
  • 举报
回复
说错了。。我是说为什么NOT IN会有这么蛋疼的计划。。
黄_瓜 2012-06-03
  • 打赏
  • 举报
回复
但是执行速度应该一样
黄_瓜 2012-06-03
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]

SQL code
select * from b except select * from a
[/Quote]
这个结果会不一样的

34,575

社区成员

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

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