关于exists的疑问

chenxin2835 chenxin2835 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
最近在进行2000向2005转变的学习,遇到一个exists使用的问题.
在删除重复行中(有唯一ID)exists的使用和in的使用效果相同,但是在更新语句上
exists和in的效果就不同了,觉得奇怪.如下是测试代码

删除重复行的
if object_id('table2')is not null drop table table2
create table table2(id int identity(1,1) primary key, name varchar(2))
insert into table2(name)
select 'a' union all
select 'a' union all
select 'b' union all
select 'c' union all
select 'c' union all
select 'd'

select * from table2

delete table2 from table2 a where exists (select 1 from table2 where name=a.name and id<a.id)

delete table2 from table2 a where name in (select name from table2 where name=a.name and id<a.id)

更新行的
if object_id('tba')is not null drop table tba
if object_id('tbb')is not null drop table tbb
create table tba(c1 varchar(10),c2 varchar(10),c3 int)
insert tba select
'str1 ','str2', null union select
'str3 ','str4', null union select
'str5 ','str6', null union select
'str7 ','str8', null

create table tbb(c1 varchar(10),c2 varchar(10))
insert tbb select
'str7 ','str8' union select
'str1 ','str3' union select
'str11 ','str22' union select
'str3 ','str4'
go


update tba
set c3=1
where c1 in(select tba.c1 from tba,tbb where tba.c1=tbb.c1 and tba.c2=tbb.c2)

update tba
set c3=1
where exists(select 1 from tba,tbb where tba.c1=tbb.c1 and tba.c2=tbb.c2)

select * from tba
...全文
评论 11
收藏 已收藏
分享
返回顶部
chenxin2835
MS-SQL Server 34,877 成员 254,635 内容