SQL Server exists,not exists的用法
2022-11-12 09:54:04
内容摘要
这篇文章主要为大家详细介绍了SQL Server exists,not exists的用法,具有一定的参考价值,可以用来参考一下。
对此感兴趣的朋友,看看idc笔记做的技术笔记!
学生表:create table
文章正文
这篇文章主要为大家详细介绍了SQL Server exists,not exists的用法,具有一定的参考价值,可以用来参考一下。
对此感兴趣的朋友,看看idc笔记做的技术笔记!
1 2 3 4 5 | 学生表:create table student ( id number(8) primary key, name varchar2(10),deptment number(8) ) |
1 2 3 4 5 6 | 选课表: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) ) |
1 2 3 4 5 6 | 课程表:create table COURSE ( ID NUMBER(8) not null, C_NAME VARCHAR2(20), C_NO VARCHAR2(10) ) |
1 2 3 4 5 6 7 | student表的数据: ID NAME DEPTMENT_ID ---------- --------------- ----------- 1 echo 1000 2 spring 2000 3 smith 1000 4 liter 2000 |
1 2 3 4 5 6 | course表的数据: ID C_NAME C_NO ---------- -------------------- -------- 1 数据库 data1 2 数学 month1 3 英语 english1 |
1 2 3 4 5 6 7 8 9 | 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 | 1.查询选修了所有课程的学生id、name:(即这一个学生没有一门课程他没有选的。) |
1 | 分析:如果有一门课没有选,则此时(1)select * from select_course sc where sc.student_id=ts.id |
1 | and sc.course_id=c.id存在null, |
1 | 这说明(2)select * from course c 的查询结果中确实有记录不存在(1查询中),查询结果返回没有选的课程, |
1 | 此时select * from t_student ts 后的not exists 判断结果为false,不执行查询。 |
1 2 3 | 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)); |
1 2 3 | ID NAME DEPTMENT_ID ---------- --------------- ----------- 1 echo 1000 |
1 | 2.查询没有选择所有课程的学生,即没有全选的学生。(存在这样的一个学生,他至少有一门课没有选), |
1 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 ), |
1 | 因此select id,name from t_student 将执行查询(id为子查询中t_student.id )。 |
1 | SQL> select id,name from t_student where exists |
1 | (select * from course where not exists |
1 | (select * from select_course sc where student_id=t_student.id and course_id=course.id)); |
1 2 3 4 5 | ID NAME ---------- --------------- 2 spring 3 smith 4 liter |
1 | 3.查询一门课也没有选的学生。(不存这样的一个学生,他至少选修一门课程), |
1 | 分析:如果他选修了一门select * from course结果集不为空,not exists 判断结果为false; |
1 | select id,name from t_student 不执行查询。 |
1 | SQL> select id,name from t_student where not exists |
1 | (select * from course where exists |
1 | (select * from select_course sc where student_id=t_student.id and course_id=course.id)); |
1 2 3 | ID NAME ---------- --------------- 4 liter |
1 2 | 4.查询至少选修了一门课程的学生。 SQL> select id,name from t_student where exists |
1 | (select * from course where exists |
1 | (select * from select_course sc where student_id=t_student.id and course_id=course.id)); |
1 2 3 4 5 | ID NAME ---------- --------------- 1 echo 2 spring 3 smith |
注:关于SQL Server exists,not exists的用法的内容就先介绍到这里,更多相关文章的可以留意
代码注释