怎么用用sql语句中的not exists来写语句?
2个回答
2013-08-13
展开全部
USE pubs
GO
SELECT DISTINCT pub_name
FROM publishers
WHERE EXISTS
(SELECT *
FROM titles
WHERE pub_id = publishers.pub_id
AND type = 'business')
GO
-- Or, using the IN clause:
USE pubs
GO
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
GO
SELECT DISTINCT pub_name
FROM publishers
WHERE EXISTS
(SELECT *
FROM titles
WHERE pub_id = publishers.pub_id
AND type = 'business')
GO
-- Or, using the IN clause:
USE pubs
GO
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
推荐于2016-06-02
展开全部
使用 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')
下面是结果集:
pub_name
----------------------------------------
Binnet & Hardley
Five Lakes Publishing
Ramona Publishers
GGG&G
Scootney Books
Lucerne Publishing
(6 row(s) affected)
下面的查询查找已经不销售的书的名称。
USE pubs
SELECT title
FROM titles
WHERE NOT EXISTS
(SELECT title_id
FROM sales
WHERE title_id = titles.title_id)
下面是结果集:
title
----------------------------------
The Psychology of Computer Cooking
Net Etiquette
(2 row(s)
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')
下面是结果集:
pub_name
----------------------------------------
Binnet & Hardley
Five Lakes Publishing
Ramona Publishers
GGG&G
Scootney Books
Lucerne Publishing
(6 row(s) affected)
下面的查询查找已经不销售的书的名称。
USE pubs
SELECT title
FROM titles
WHERE NOT EXISTS
(SELECT title_id
FROM sales
WHERE title_id = titles.title_id)
下面是结果集:
title
----------------------------------
The Psychology of Computer Cooking
Net Etiquette
(2 row(s)
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询