使用EXISTS语句注意点

1.使用EXISTS语句,其目标列一般用“*”,因为带EXISTS的子查询只返回真值或假值,给出列名无实际意义

2.使用EXISTS语句一定要注意上下两个表之间要建立联系。

例如,查询所有选修了1号课程的学生姓名。

错误做法是:

select Sname
From student
where Exists
        (
              select *
              from SC
              WHERE Cno='1';
        )        

因为二者之间没有建立联系。所有查询失败。

正确做法是

select Sname
From student
where Exists
        (
              select *
              from SC
              WHERE Sno=student.Sno  AND Cno='1';
        )        

2,使用NOT EXISTS 表示不存在。

例2:查询没有选修1号课程的学生名称。

select Sname
From student
where NOT Exists
        (
              select *
              from SC
              WHERE Sno=student.Sno  AND Cno='1';
        )    

 

posted @ 2016-06-07 15:52  美好的明天  阅读(674)  评论(0)    收藏  举报