[not] in/exists 与 带TOP的子查询

当子查询中带TOP时,有连接条件和无连接条件结果是不一样的。

in和exists子句的结构也不一样。

看例子。

[@more@]

create table a(id int)

insert into a
select 1
union
select 2
union
select 3
union
select 4
union
select 5

create table b(id int)

insert into b
select 1
union
select 2
union
select 3

-- 1
select * from a
where id in(select top 2 id from b)
-- 2
select * from a
where id in(select top 2 id from b where b.id = a.id)
-- 3
select * from a
where exists(select top 2 id from b where b.id = a.id)
-- 4
select * from a
where exists(select 1 from (select top 2 id from b) c where c.id = a.id)

我们可以看出,1和4是正确的,3和4不是我盟想要的结果。
加上not也一样:

-- 1
select * from a
where id not in(select top 2 id from b)
-- 2
select * from a
where id not in(select top 2 id from b where b.id = a.id)
-- 3
select * from a
where not exists(select top 2 id from b where b.id = a.id)
-- 4
select * from a
where not exists(select 1 from (select top 2 id from b) c where c.id = a.id)

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/66009/viewspace-1012948/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/66009/viewspace-1012948/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值