欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SQL中exists的使用方法

程序员文章站 2023-12-14 20:19:58
有一个查询如下: 复制代码 代码如下: select c.customerid, companyname from customers c where exists( se...
有一个查询如下:
复制代码 代码如下:

select c.customerid, companyname
from customers c
where exists(
select orderid from orders o
where o.customerid = cu.customerid)

这里面的exists是如何运作呢?子查询返回的是orderid字段,可是外面的查询要找的是customerid和companyname字段,这两个字段肯定不在orderid里面啊,这是如何匹配的呢?
exists用于检查子查询是否至少会返回一行数据,该子查询实际上并不返回任何数据,而是返回值true或false。
exists 指定一个子查询,检测行的存在。语法:exists subquery。参数 subquery 是一个受限的 select 语句 (不允许有 compute 子句和 into 关键字)。结果类型为 boolean,如果子查询包含行,则返回 true。
在子查询中使用 null 仍然返回结果集
这个例子在子查询中指定 null,并返回结果集,通过使用 exists 仍取值为 true。
复制代码 代码如下:

select categoryname
from categories
where exists (select null)
order by categoryname asc

比较使用 exists 和 in 的查询
这个例子比较了两个语义类似的查询。第一个查询使用 exists 而第二个查询使用 in。注意两个查询返回相同的信息。
复制代码 代码如下:

select distinct pub_name
from publishers
where exists
(select *
from titles
where pub_id = publishers.pub_id
and type = \'business\')

复制代码 代码如下:

select distinct pub_name
from publishers
where pub_id in
(select pub_id
from titles
where type = \'business\')

比较使用 exists 和 = any 的查询
本示例显示查找与出版商住在同一城市中的作者的两种查询方法:第一种方法使用 = any,第二种方法使用 exists。注意这两种方法返回相同的信息。
复制代码 代码如下:

select au_lname, au_fname
from authors
where exists
(select *
from publishers
where authors.city = publishers.city)

复制代码 代码如下:

select au_lname, au_fname
from authors
where city = any
(select city
from publishers)

比较使用 exists 和 in 的查询
本示例所示查询查找由位于以字母 b 开头的城市中的任一出版商出版的书名:
复制代码 代码如下:

select title
from titles
where exists
(select *
from publishers
where pub_id = titles.pub_id
and city like \'b%\')

复制代码 代码如下:

select title
from titles
where pub_id in
(select pub_id
from publishers
where city like \'b%\')

使用 not exists
not exists 的作用与 exists 正相反。如果子查询没有返回行,则满足 not exists 中的 where 子句。本示例查找不出版商业书籍的出版商的名称:
复制代码 代码如下:

select pub_name
from publishers
where not exists
(select *
from titles
where pub_id = publishers.pub_id
and type = \'business\')
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嵌套时的返回值弄明白

上一篇:

下一篇: