哪位大侠可以帮忙区分一下exists和in?

billdavid 2003-05-30 05:01:21
能举几个例子吗?
...全文
25 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
billdavid 2003-05-30
  • 打赏
  • 举报
回复
二者有什么区别呢?在功能上完全等价?
在执行效率上,IN是不是较高?
刚才查了一下书,好像IN执行时是由子查询到查询,而EXISTS是由查询到子查询,逐一检查查询中各条记录是否满足子查询,一旦子查询中未出现任何与查询数据库字段相关的约束信息,子查询就一点约束力都没有了,只要子查询有返回,而IN却总有约束力.
pengdali 2003-05-30
  • 打赏
  • 举报
回复
在有些情况下用exists比in好

select * from T1 where exists (select 1 from t2 where 编号1=t1.编号1 and 编号2=t2.编号2)
wgy2008 2003-05-30
  • 打赏
  • 举报
回复
B. 比较使用 EXISTS 和 IN 的查询
这个例子比较了两个语义类似的查询。第一个查询使用 EXISTS 而第二个查询使用 IN。注意两个查询返回相同的信息。

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

(2 row(s) affected)


愉快的登山者 2003-05-30
  • 打赏
  • 举报
回复
a (id) 1,2
b (id) 1,3

select id from a where id in (select id from b)
select id from a where exists (select id from b where id = a.id)
id
1
select id from a where id not in (select id from b)
select id from a where not exists (select id from b where id = a.id)
id
2


愉快的登山者


◢◣◢◣◢◣

34,871

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧