select * from table1 A where not exists (SELECT * FROMtable2 B whereB.col1 = A.col1) 结果就正确,有一条数据显示。 转载注明出处:http://x- spirit.iyunv.com/、http: //www.blogjava.net/zhangwei217245/
经过一番搜索,原以为是子查询结果集太大的原因。
后来有网上强人指点:子查询里面有空集。即子查询的结果集里面有NULL的结果。
把查询语句修改成:
语句3 :
Select * from table1A where A.col1 not in( select col1 from table2B where B.col1 is not null )
有人说EXISTS的性能比IN要好。但这是很片面的。我们来看看EXISTS的执行过程:
select * fromt1 where exists (select * from t2where t2.col1 = t1.col1 )
相当于:
for x in ( select * from t1)
loop
if (exists ( select * fromt2 where t2.col1 = x.col1 )
then
OUTPUTTHERECORD in x
end if
end loop
转载注明出处:http://x- spirit.iyunv.com/、http: //www.blogjava.net/zhangwei217245/
也就是说,EXISTS语句实际上是通过循环外部查询的结果集,来过滤出符合子查询标准的结果集。于是外部查询的结果集数量对该语句执行性能影响最大,故如果外部查询的结果集数量庞大,用EXISTS语句的性能也不一定就会好很多。
转载注明出处:http://x- spirit.iyunv.com/、http: //www.blogjava.net/zhangwei217245/
当然,有人说NOT IN是对外部查询和子查询都做了全表扫描,如果有索引的话,还用不上索引,但是NOT EXISTS是做连接查询,所以,如果连接查询的两列都做了索引,性能会有一定的提升。
当然至于实际的查询效率,我想还是具体情况具体分析吧。
那么我们不妨来分析一下语句2为什么能够的到正确的结果吧:
语句2是这样的: select * from table1 A where not exists (SELECT B.col1 FROM table2 B where B.col1 = A.col1)
实际上是这样的执行过程:
for x in ( select * from table1 A )
loop
if (notexists ( select * fromtable2 B whereB.col1 = x.col1 )
then
OUTPUTTHERECORD in x
end if
end loop
转载注明出处:http://x- spirit.iyunv.com/、http: //www.blogjava.net/zhangwei217245/
由于表A中不包含NULL的记录,所以,遍历完表A,也只能挑出表A中独有的记录。