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

关于sql2000中exists的问题
两个表 tb_student(学生表)和tb_score(成绩表)

select   *   from   tb_student
where   exists   (select   *   from   tb_score   where  
                            course_no= 'c801 ')
返回tb_student表中所有记录

这个我可以理解,就是说exists里面返回 真  然后执行外层的查询.

但是 select   *   from   tb_student
where   exists   (select   *   from   tb_score   where  
                            course_no= 'c801 '   and   tb_student.student_no=student_no)      
  返回

一条记录.

我看过一本书,说exists只是返回 真 或者 假

同样的exists里面返回的是  真  为什么就一条记录????

多了这一个条件 tb_student.student_no=student_no,它是怎么执行的????

------解决方案--------------------
个人理解:
exists是存在于的意思.
第一个例子中,exists后面的数据与exists前面的不相关,所以可以都取出
第二个例子中,exists后面的数据与前面的表中的数据有了关联,所以只能取一条数据
用这个也是一样的
select * from tb_student
where exists (select 1 from tb_score where
course_no= 'c801 ' and tb_student.student_no=student_no)
------解决方案--------------------
很容易理解,只有一条记录满足:
  course_no= 'c801 ' and tb_student.student_no=student_no
其它的都不满足,不满足就是“假”,当然只返回满足——“真”的一条记录。

如果改成 OR 必然还是返回所有记录:
  course_no= 'c801 ' or tb_student.student_no=student_no