SQL中exists的使用方法

2020-07-10 08:07:05易采站长站整理

ORDER BY pub_name

又比如以下 SQL 语句:

select distinct 姓名 from xs
where not exists (
select * from kc
where not exists (
select * from xs_kc
where 学号=xs.学号 and 课程号=kc.课程号
)

把最外层的查询xs里的数据一行一行的做里层的子查询。
中间的 exists 语句只做出对上一层的返回 true 或 false,因为查询的条件都在 where 学号=xs.学号 and 课程号=kc.课程号这句话里。每一个 exists 都会有一行值。它只是告诉一层,最外层的查询条件在这里成立或都不成立,返回的时候值也一样回返回上去。直到最高层的时候如果是 true(真)就返回到结果集。为 false(假)丢弃。

where not exists
select * from xs_kc
where 学号=xs.学号 and 课程号=kc.课程号

这个 exists 就是告诉上一层,这一行语句在我这里不成立。因为他不是最高层,所以还要继续向上返回。
select distinct 姓名 from xs where not exists (这里的 exists 语句收到上一个为 false 的值。他在判断一下,结果就是为 true(成立),由于是最高层所以就会把这行的结果(这里指的是查询条件)返回到结果集。
几个重要的点:
最里层要用到的醒询条件的表比如:xs.学号、kc.课程号等都要在前面的时候说明一下select * from kc,select distinct 姓名 from xs
不要在太注意中间的exists语句.
把exists和not exists嵌套时的返回值弄明白

相关文章 大家在看