日期:2014-05-18  浏览次数:20425 次

not exist与not in的区别
create   table   t
(column1   int       column2   varchar(10)     column3   varchar(10)   column4   varchar(10))
insert   into   t
select   1                         'B '                   'C '                   'D '   union   all
select   2                         'B '                   'C '                   'E '   union   all
select   3                         'F '                   'F '                   'H '  

select   *   from   t   a
where   not   exists  
(select   *   from   t   where   a.column2=t.column2   and   a.column3=t.column3   and   a.column1 <t.column1)


select   *   from   t   a  
where   a.column1   not   in  
(select   column1   from   t   where   a.column2=t.column2   and   a.column3=t.column3   and   a.column1 <t.column1)
drop   table   t

谁帮测下这个SQL   第二个SQL为什么不排除第一行啊?  



------解决方案--------------------
select *
from t a
where not exists
(select * from t
where a.column2=t.column2 and a.column1 <t.column1 )

--1 1 <2 not exists为假 (条件为 'b '=t.column2 and 1 <t.column1 )
--2 2 <??? OK (条件为 'b '=t.column2 and 2 <t.column1 )
--3 3 <?? OK (条件为 'F '=t.column2 and 3 <t.column1 )


select *
from t a
where a.column1 not in
(select column1 from t
where a.column2=t.column2 and a.column1 <t.column1)
--1 条件为 1 not in (2) -- OK 子查询条件 'b '=t.column2 amd 1 <t.column1
--2 条件为 1 not in (??) -- OK 子查询条件 'b '=t.column2 amd 2 <t.column1
--这个??不知道怎么表示,相当于一个空的数组吧
--3 同上
------解决方案--------------------
按你的题
你可以把
not in

not exists

not in分解成
select * from t where col1 not in (....1 <1)
union all
select * from t where col1 not in (....1 <2)
union all
select * from t where col1 not in (....1 <3)

not exists 分解成
select * from t where not exsits
(select 1 <1
union all
select 1 <2
union all
select 1 <3
)


当然这只是方便理解而转化的... sql 到底是怎么处理的 偶也不清楚


------解决方案--------------------
welove1983的说法有点出入.
---------------------------


not in
即:
where x not in
(
select statement
where
condition 1
AND
condition 2
..
AND
condition N
)

逻辑上是 "与的非 " 运算, 这个逻辑运算可转换为 "非的与 "
即 _____ _ _
A * B = A * B

而楼上的写法 UINION ALL 操作是 或操作,那么相当于是 将 与的非 转成 或了
即 _____ _ _
A * B = A U B

取条件结果的非. 比如: A{1,2,3},B{1} 在这两个集合中,A集合