在网上查了查,这个问题算是搞清楚了,请论坛各位路过的兄弟踩踩,应该没问题吧。
create table student (sno int,sname varchar(50),ssex varchar(50),sage int,sdept varchar(20))
create table sc (cno int,sno int,grade int)
create table course (cno int ,canme varchar(50),cpno varchar(50),ccredit int)insert into student select '95001','张三','男','20','cs'
union all select '95002','李四','女','19','is'
union all select '95003','王五','女','18','ma'
union all select '95004','李勇','男','19','is'insert into sc select '95001','1','90'
union all select '95001','2','88'
union all select '95001','3','78'
union all select '95002','1','58'
union all select '95002','2','63'
union all select '95003','1','99'
union all select '95004','4','99'
union all select '95004','1','99'insert into course select '1','数据库','','4'
union all select '2','网络','','2'
union all select '3','程序','','6' 
执行in时,首先首先执行子查询,并将获得的结果存放在一个加了索引的临时表中,在执行子查询之前,系统先将主查询挂起,在执行子查询执行完毕,再进行主查询。
而exists,首先检查主查询,然后运行子查询直到找到第一个匹配记录。对于加了索引的表,的确高效率。
但并不能说in和exists哪一个效率更高,而是要看怎么用。以下程序分别用in 和exists来编写,以比较他们之间的不同。问题一:选过全部课程的学生名字
有两种方法,第一种是in 这个很简单,就不说了。select * from student t where sno in(
select sno  from sc group by sno having count(sc.cno)=(select count(*) from course)
第二种是 嵌套not exists
select * from student t where not exists 
(select * from course s where not exists 
(select * from sc where t.sno=sc.sno and s.cno= sc.cno )--s.cno= sc.cno and t.sno=sc.sno  )
)
这个问题要这样看,该学生没有一门课程没有选,否定之否定,就是都选了。
not exists运行时,首先取student表的第一条记录 95001,对于这一次运行,可以分解成下面片段
select * from course s where not exists 
(select * from sc where s.cno= sc.cno and sc.sno=95001 )
然后对其not exists,结果就是最终数据的一条记录。
之后,再取student的第二条记录95002,重复上述过程,结果就是想要的了。问题二:全部学生都没有选的课程
select * from course s where cno not in(
select cno from sc group by cno having count(sc.cno)!=0 
)
select cname from course s where not exists (
select * from student t where  exists (
select * from sc where sc.sno=t.sno and sc.cno =s.cno)
)
问题三:选择了全部课程的学生select * from student t where sno  in(
select sno  from sc group by sno having count(sc.cno)=(select count(*) from course)
                                     )select cname from course s where not exists (
select * from student t where not exists (
select * from sc where sc.sno=t.sno and sc.cno =s.cno)
)