之前没注意到这两者的差别。
其实,这里还是有一定的陷阱的。
先看下代码:
select count(*) from ( ( select sc.xh from "JISUANJI"."STUDENTCHECK" sc ) union ( select stu.XH as xh from "JISUANJI"."CVARIABLE" cv , "JISUANJI"."SEMESTER" s , "JISUANJI"."STUBASICINFO" stu , "JISUANJI"."COURSE" c,"JISUANJI"."SCOURSE" sc where cv.SID = s.SID and cv.SCID = sc.SCID and sc.xkkh = c.coursecode and cv.XH = stu.XH and 1=1 and (stu.xh not exists (select sc.xh from "JISUANJI"."STUDENTCHECK" sc)) ) ) t1(运行错误,会报无效的关系运算符)
不细心地认为这是没有问题的,但是,它确实存在着差别。
select count(*) from ( ( select sc.xh from "JISUANJI"."STUDENTCHECK" sc ) union ( select stu.XH as xh from "JISUANJI"."CVARIABLE" cv , "JISUANJI"."SEMESTER" s , "JISUANJI"."STUBASICINFO" stu , "JISUANJI"."COURSE" c,"JISUANJI"."SCOURSE" sc where cv.SID = s.SID and cv.SCID = sc.SCID and sc.xkkh = c.coursecode and cv.XH = stu.XH and 1=1 and (stu.xh not in (select sc.xh from "JISUANJI"."STUDENTCHECK" sc)) ) ) t1
运行出错的代码应该改为:
select count(*) from ( ( select sc.xh from "JISUANJI"."STUDENTCHECK" sc ) union ( select stu.XH as xh from "JISUANJI"."CVARIABLE" cv , "JISUANJI"."SEMESTER" s , "JISUANJI"."STUBASICINFO" stu , "JISUANJI"."COURSE" c,"JISUANJI"."SCOURSE" sc where cv.SID = s.SID and cv.SCID = sc.SCID and sc.xkkh = c.coursecode and cv.XH = stu.XH and 1=1 and ( not exists (select sc.xh from "JISUANJI"."STUDENTCHECK" sc)) ) ) t1
1.使用方式上的差别。
where stu.xh not in
where ont exits
exists是不需要加上字段名字的。
有时候你会发现,运行好像没问题。
但是,它还是存在的问题的!数值也行有时候是正确的。这可能误导的!
select count(*) from (
( select sc.xh from "JISUANJI"."STUDENTCHECK" sc )
union
( select stu.XH as xh
from "JISUANJI"."CVARIABLE" cv , "JISUANJI"."SEMESTER" s , "JISUANJI"."STUBASICINFO" stu , "JISUANJI"."COURSE" c,"JISUANJI"."SCOURSE" sc
where cv.SID = s.SID and cv.SCID = sc.SCID and sc.xkkh = c.coursecode and cv.XH = stu.XH and 1=1
and ( not exists (select sc.xh from "JISUANJI"."STUDENTCHECK" sc where stu.xh= sc.xh))
)
) t1
这才是最终的exists的使用方法。
exists关键字使用的时候,需要关联的!
为什么呢?
这个就是in/exists之间的原理的差别了
很多时候,有人跟你说,都使用exists,exists比in效率高!
但是,这个不是正确的了。可以说,exists使用比较多!
结论是:
如果两个表中一个较小,一个是大表,则子查询表大的用exists,子查询表小的用in
如果两个表都差不多一样大的话,效率是差不多的!
这是因为,
in 是把外表和内表作hash join,而exists是对外表作loop,每次loop再对内表进行查询。每次循环查的时候,和in模式不一样的地方是:返回值是真或假,是真就输出。