专注于互联网--专注于架构

最新标签
网站地图
文章索引
Rss订阅

首页 »数据库 » ifnotexists:sqlserver exists not exists的使用方法 »正文

ifnotexists:sqlserver exists not exists的使用方法

来源: 发布时间:星期二, 2009年12月8日 浏览:146次 评论:0
学生表:create table student
(
id number(8) primary key,
name varchar2(10),deptment number(8)
)

选课表:create table select_course
(
ID NUMBER(8) primary key,
STUDENT_ID NUMBER(8) foreign key (COURSE_ID) references course(ID),
COURSE_ID NUMBER(8) foreign key (STUDENT_ID) references student(ID)
)

课程表:create table COURSE
(
ID NUMBER(8) not null,
C_NAME VARCHAR2(20),
C_NO VARCHAR2(10)
)

student表数据:
ID NAME DEPTMENT_ID
---------- --------------- -----------
1 echo 1000
2 spring 2000
3 smith 1000
4 liter 2000

course表数据:
ID C_NAME C_NO
---------- -------------------- --------
1 数据库 data1
2 数学 month1
3 英语 english1

select_course表数据:
ID STUDENT_ID COURSE_ID
---------- ---------- ----------
1 1 1
2 1 2
3 1 3
4 2 1
5 2 2
6 3 2

1.查询选修了所有课程学生id、name:(即这个学生没有门课程他没有选)

分析:如果有门课没有选则此时(1)select * from select_course sc where sc.student_id=ts.id

and sc.course_id=c.id存在null

这介绍说明(2)select * from course c 查询结果中确实有记录不存在(1查询中)查询结果返回没有选课程

此时select * from t_student ts 后not exists 判断结果为false不执行查询

SQL> select * from t_student ts where not exists
(select * from course c where not exists
(select * from select_course sc where sc.student_id=ts.id and sc.course_id=c.id));

ID NAME DEPTMENT_ID
---------- --------------- -----------
1 echo 1000

2.查询没有选择所有课程学生即没有全选学生(存在这样个学生他至少有门课没有选)

分析:只要有个门没有选即select * from select_course sc where student_id=t_student.id and course_id
=course.id 有条为空即not exists null 为true,此时select * from course有查询结果(id为子查询中course.id )

因此select id,name from t_student 将执行查询(id为子查询中t_student.id )

SQL> select id,name from t_student where exists

(select * from course where not exists

(select * from select_course sc where student_id=t_student.id and course_id=course.id));

ID NAME
---------- ---------------
2 spring
3 smith
4 liter

3.查询门课也没有选学生(不存这样个学生他至少选修门课程)

分析:如果他选修了门select * from course结果集不为空not exists 判断结果为false;

select id,name from t_student 不执行查询

SQL> select id,name from t_student where not exists

(select * from course where exists

(select * from select_course sc where student_id=t_student.id and course_id=course.id));

ID NAME
---------- ---------------
4 liter

4.查询至少选修了门课程学生
SQL> select id,name from t_student where exists

(select * from course where exists

(select * from select_course sc where student_id=t_student.id and course_id=course.id));

ID NAME
---------- ---------------
1 echo
2 spring
3 smith

标签:ifnotexists
0

相关文章

读者评论

发表评论

  • 昵称:
  • 内容: