共計 2535 個字符,預計需要花費 7 分鐘才能閱讀完成。
今天就跟大家聊聊有關 SQL 中如何使用 EXISTS,可能很多人都不太了解,為了讓大家更加了解,丸趣 TV 小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。
EXISTS
指定一個子查詢,檢測行的存在。
語法
EXISTS subquery
參數
subquery
是一個受限的 SELECT 語句 (不允許有 COMPUTE 子句和 INTO 關鍵字)。有關更多信息,請參見 SELECT 中有關子查詢的討論。
結果類型
Boolean
結果值
如果子查詢包含行,則返回 TRUE。
示例 A. 在子查詢中使用 NULL 仍然返回結果集
這個例子在子查詢中指定 NULL,并返回結果集,通過使用 EXISTS 仍取值為 TRUE。
USE Northwind
SELECT CategoryName
FROM Categories
WHERE EXISTS (SELECT NULL)
ORDER BY CategoryName ASC
GO
B. 比較使用 EXISTS 和 IN 的查詢
這個例子比較了兩個語義類似的查詢。第一個查詢使用 EXISTS 而第二個查詢使用 IN。注意兩個查詢返回相同的信息。
USE pubs
SELECT DISTINCT pub_name
FROM publishers
WHERE EXISTS
(SELECT *
FROM titles
WHERE pub_id = publishers.pub_id
AND type = \ business\ )
-- Or, using the IN clause:
USE pubs
SELECT distinct pub_name
FROM publishers
WHERE pub_id IN
(SELECT pub_id
FROM titles
WHERE type = \ business\ )
GO
下面是任一查詢的結果集:
pub_name
----------------------------------------
Algodata Infosystems
New Moon Books
(2 row(s) affected)
C. 比較使用 EXISTS 和 = ANY 的查詢
本示例顯示查找與出版商住在同一城市中的作者的兩種查詢方法:第一種方法使用 = ANY,第二種方法使用 EXISTS。注意這兩種方法返回相同的信息。
USE pubs
SELECT au_lname, au_fname
FROM authors
WHERE exists
(SELECT *
FROM publishers
WHERE authors.city = publishers.city)
-- Or, using = ANY
USE pubs
SELECT au_lname, au_fname
FROM authors
WHERE city = ANY
(SELECT city
FROM publishers)
GO
下面是任一查詢的結果集:
au_lname au_fname
---------------------------------------- --------------------
Carson Cheryl
Bennet Abraham
(2 row(s) affected)
D. 比較使用 EXISTS 和 IN 的查詢
本示例所示查詢查找由位于以字母 B 開頭的城市中的任一出版商出版的書名:
USE pubs
SELECT title
FROM titles
WHERE EXISTS
(SELECT *
FROM publishers
WHERE pub_id = titles.pub_id
AND city LIKE \ B%\ )
-- Or, using IN:
USE pubs
SELECT title
FROM titles
WHERE pub_id IN
(SELECT pub_id
FROM publishers
WHERE city LIKE \ B%\ )
GO
下面是任一查詢的結果集:
title
------------------------------------------------------------------------
The Busy Executive\ s Database Guide
Cooking with Computers: Surreptitious Balance Sheets
You Can Combat Computer Stress!
Straight Talk About Computers
But Is It User Friendly?
Secrets of Silicon Valley
Net Etiquette
Is Anger the Enemy?
Life Without Fear
Prolonged Data Deprivation: Four Case Studies
Emotional Security: A New Algorithm
(11 row(s) affected)
E. 使用 NOT EXISTS
NOT EXISTS 的作用與 EXISTS 正相反。如果子查詢沒有返回行,則滿足 NOT EXISTS 中的 WHERE 子句。本示例查找不出版商業書籍的出版商的名稱:
USE pubs
SELECT pub_name
FROM publishers
WHERE NOT EXISTS
(SELECT *
FROM titles
WHERE pub_id = publishers.pub_id
AND type = \ business\ )
ORDER BY pub_name
GO
下面是結果集:
pub_name
----------------------------------------
Binnet Hardley
Five Lakes Publishing
GGG G
Lucerne Publishing
Ramona Publishers
Scootney Books
(6 row(s) affected)
看完上述內容,你們對 SQL 中如何使用 EXISTS 有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注丸趣 TV 行業資訊頻道,感謝大家的支持。